SpringBoot中如何进行统一异常处理

如何在SpringBoot项目里进行统一异常处理

本文已参与「新人创作礼」活动,一起开启掘金创作之路。

需要了解的知识

@ControllerAdvice的作用

1、处理前

==异常代码==

/**
     * 根据id获取医院设置
     *
     * @param id 查看的id编号
     * @return
     */
@ApiOperation(value = "根据id获取医院设置")
@GetMapping("/findHospById/{id}")
public Result findHospById(@PathVariable Long id) {
    // 模拟异常(因为除数不能为0)
    int a = 1 / 0;
    HospitalSet hospitalSet = hospitalSetService.getById(id);
    return Result.ok(hospitalSet);
}

==Swagger2输出结果==

image-20220202214712150

2、进行系统异常全局处理

==添加全局异常处理类==

image-20220202215154305

==代码==

package com.fafa.yygh.common.exception;

import com.fafa.yygh.common.result.Result;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 全局异常处理
 *
 * @author Sire
 * @version 1.0
 * @date 2022-02-02 21:01
 */
@ControllerAdvice
public class GlobalExceptionHandler {
    /**
     * 系统异常处理
     *
     * @param e
     * @return
     */
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Result error(Exception e) {
        e.printStackTrace();
        return Result.fail();
    }
}

==Swagger2结果==

image-20220202215407159

3、进行自定义异常处理

开发时,往往需要我们去定义处理一些异常(这里还是那上面的那个异常来做测试)

==创建自定义异常处理类==

package com.fafa.yygh.common.exception;

import com.fafa.yygh.common.result.ResultCodeEnum;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

/**
 * 自定义全局异常类
 *
 * @author qy
 */
@Data
@ApiModel(value = "自定义全局异常类")
public class YyghException extends RuntimeException {

    @ApiModelProperty(value = "异常状态码")
    private Integer code;

    /**
     * 通过状态码和错误消息创建异常对象
     *
     * @param message
     * @param code
     */
    public YyghException(String message, Integer code) {
        super(message);
        this.code = code;
    }

    /**
     * 接收枚举类型对象
     *
     * @param resultCodeEnum
     */
    public YyghException(ResultCodeEnum resultCodeEnum) {
        super(resultCodeEnum.getMessage());
        this.code = resultCodeEnum.getCode();
    }

    @Override
    public String toString() {
        return "YyghException{" +
            "code=" + code +
            ", message=" + this.getMessage() +
            '}';
    }
}

==将其添加到GlobalExceptionHandler==

/**
     * 自定义异常处理
     *
     * @param e
     * @return
     */
@ExceptionHandler(YyghException.class)
@ResponseBody
public Result divError(YyghException e) {
    return Result.build(e.getCode(), e.getMessage());
}

image-20220202215737501

==需要手动 try catch 一下==

image-20220202215919100

==效果==

swagger和系统异常处理一样

不过后台输出不一样 image-20220202220034953

猜你喜欢

转载自juejin.im/post/7124910842239254559