统一异常处理springboot

统一异常处理

一、创建统一异常处理类GlobalExceptionHandler.java

/**
 * 统一异常处理类
 */
@ControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public R error(Exception e){
        e.printStackTrace();
        return R.error();
    }
}

二、特定异常处理

@ExceptionHandler(ArithmeticException.class)
@ResponseBody
public R error(ArithmeticException e){
4
    e.printStackTrace();
5
    return R.error().message("执行了自定义异常");
6
}

三、自定义异常处理

一,创建自定义异常类

@Data
@AllArgsConstructor
@NoArgsConstructor
public class GuliException extends RuntimeException {
    @ApiModelProperty(value = "状态码")
    private Integer code;
    private String msg;
}

二、业务中需要的位置抛出GuliException

try {
    int a = 10/0;
}catch(Exception e) {
    throw new GuliException(20001,"出现自定义异常");
}

三、添加异常处理方法

@ExceptionHandler(GuliException.class)
@ResponseBody
public R error(GuliException e){
    e.printStackTrace();
    return R.error().message(e.getMsg()).code(e.getCode());
}

猜你喜欢

转载自blog.csdn.net/qq_38132995/article/details/114009414