错误处理
1.处理所有的异常信息,包括捕获不到的400、401等等(进入controller之前)
SpringBoot官方文档:
BasicErrorController可以用作自定义的基 类ErrorController。如果您想为新的内容类型添加处理程序,这特别有用(默认是text/html专门处理并为其他所有内容提供后备)。为此,请扩展BasicErrorController,添加一个@RequestMapping具有produces属性的公共方法,并创建一个新类型的 bean
@RestController
public class MyErrorController extends BasicErrorController {
public MyErrorController(ServerProperties serverProperties) {
super(new DefaultErrorAttributes(), serverProperties.getError());
}
@Override
public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {
// 获取原始错误信息
Map<String, Object> body = getErrorAttributes(request, getErrorAttributeOptions(request, MediaType.ALL));
HttpStatus status = getStatus(request);
Map<String, Object> result = new HashMap<>();
result.put("success","false");
result.put("code", body.get("status"));
result.put("errorMessage", body.get("error"));
return new ResponseEntity<>(result,status);
}
}
其中getErrorAttributes之前是使用的是isIncludeStackTrace但是报错
报错原因为:boolean无法转换为org.springframework.boot.web.error.ErrorAttributeOptions
2.自定义异常(进入controller之后的异常)
Springboot文档:
定义一个带有注释的类@ControllerAdvice来自定义 JSON 文档以返回特定控制器和/或异常类型
1.根据业务的要求来定义异常类,继承自RuntimeException。RuntimeException是一个非检查型异常,在编译过程中,并不会去检查,可以顺利编译通过
public class MyException extends RuntimeException{
private String code;
private String errorMessage;
public MyException(String code,String errorMessage){
this.code = code;
this.errorMessage = errorMessage;
}
public MyException(ResultCodeEnum resultCodeEnum){
this.code = resultCodeEnum.getCode();
this.errorMessage = resultCodeEnum.getMessage();
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getErrorMessage() {
return errorMessage;
}
public void setErrorMessage(String errorMessage) {
this.errorMessage = errorMessage;
}
@Override
public String toString() {
final StringBuffer sb = new StringBuffer("MyException{");
sb.append("code='").append(code).append('\'');
sb.append(", errorMessage='").append(errorMessage).append('\'');
sb.append('}');
return sb.toString();
}
}
1.使用@ExceptionHandler注解捕获指定或自定义的异常;
2.使用@ControllerAdvice集成@ExceptionHandler的方法到一个类中;
@ControllerAdvice
public class MyControllerAdvice extends ResponseEntityExceptionHandler {
private static final Logger logger = LoggerFactory.getLogger(MyControllerAdvice.class);
/**
* 自定义异常处理
* @param e
* @return
*/
@ResponseBody
@ExceptionHandler({ MyException.class })
public E error(MyException e) {
logger.error("catch exception,", e);
return E.error(e.getErrorMessage());
}
/**
* 通用异常处理
* @param e
* @return
*/
@ResponseBody
@ExceptionHandler({Exception.class})
public E error(Exception e){
return E.error();
}
/*--------- 指定异常处理 ---------**/
/**
* 空指针异常处理
* @param e
* @return
*/
@ResponseBody
@ExceptionHandler({NullPointerException.class})
public E error(NullPointerException e){
return E.error(ResultCodeEnum.NULL_POINTER_ERROR);
}
@ResponseBody
@ExceptionHandler({ArithmeticException.class})
public E error(ArithmeticException e){
return E.error("除母不能为0");
}
}
2022年08月02日