springboot-统一异常处理

一、统一异常处理

1、创建统一异常处理器

在service-base中创建统一异常处理类GlobalExceptionHandler.java:

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

二、处理特定异常

1、添加异常处理方法

GlobalExceptionHandler.java中添加

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

三、自定义异常

1、创建自定义异常类

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

2、添加异常处理方法

GlobalExceptionHandler.java中添加

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

3、业务中需要的位置抛出XycException

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

猜你喜欢

转载自blog.csdn.net/qq_46343559/article/details/113734974
今日推荐