ControllerAdvice+ExceptionHandler全局捕获异常
自定义异常类
public class CustomException extends RuntimeException{Integer code;String msg;public CustomException( Integer code, String msg) {this.code = code;this.msg = msg;}
}
全局捕获自定义异常
@ControllerAdvice注解是Spring3.2中新增的注解,学名是Controller增强器,作用是给Controller控制器添加统一的操作或处理。
ExceptionHandler选择需要捕获的异常,当出现异常时返回Result对象,统一了接口的返回形式。
@RestControllerAdvice
public class GlobalExceptionHandler {@ExceptionHandler(CustomException.class)public Result erro(CustomException customException){return new Result(customException.msg,customException.code);}
}
controller方法
num为0时抛出异常,不为0时返回Result对象。
@GetMapping("/hello_withparam")public Result<People> hello_param(Integer num){if(num==0){throw new CustomException(202,"num is 0");}return new Result(null,200);}