自定义异常
默认的异常都是jdk自带的,有时候需要使用自己定义的异常
自定义异常步骤:
1 创建自定义异常类继承RunException
@Data
@NoArgsConstructor // 生成无参构造
@AllArgsConstructor
public class GuliException extends RuntimeException {
private Integer code; // 状态码
private String msg; // 异常信息
}
2 手动抛出自定义异常
try { int a = 10/0; }catch(Exception e) { throw new GuliException(20001, "出现自定义异常"); }
3 异常处理
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(Exception.class)
@ResponseBody
public R exceptionHandle(Exception e) {
e.printStackTrace();
return R.error().message("执行了全局异常处理。。。");
}
// 特定异常
@ExceptionHandler(ArithmeticException.class)
@ResponseBody
public R exceptionHandle(ArithmeticException e) {
e.printStackTrace();
return R.error().message("执行了ArithmeticException异常处理。。。");
}
// 自定义异常
@ExceptionHandler(GuliException.class)
@ResponseBody
public R error(GuliException e){
e.printStackTrace();
return R.error().message(e.getMsg()).code(e.getCode());
}
}
如有不当,欢迎指正

浙公网安备 33010602011771号