/**
* 错误处理相关配置
*/
@Configuration
public class ErrorConfiguration {
@Bean
public MyErrorController basicErrorController(ErrorAttributes errorAttributes, ServerProperties serverProperties,
ObjectProvider<List<ErrorViewResolver>> errorViewResolversProvider) {
return new MyErrorController(errorAttributes, serverProperties.getError(),
errorViewResolversProvider.getIfAvailable());
}
}
/**
* 自定义错误处理controller
*/
public class MyErrorController extends BasicErrorController{
public MyErrorController(ErrorAttributes errorAttributes, ErrorProperties errorProperties, List<ErrorViewResolver> errorViewResolvers) {
super(errorAttributes, errorProperties, errorViewResolvers);
}
@Override
protected Map<String, Object> getErrorAttributes(HttpServletRequest request, boolean includeStackTrace) {
Map<String, Object> attrs = super.getErrorAttributes(request, includeStackTrace);
attrs.remove("timestamp");
attrs.remove("status");
attrs.remove("error");
attrs.remove("exception");
attrs.remove("path");
String errorCode = (String) attrs.get("message");
ErrorEnum errorEnum = ErrorEnum.getByCode(errorCode);
attrs.put("message",errorEnum.getMessage());
attrs.put("code",errorEnum.getCode());
attrs.put("canRetry",errorEnum.isCanRetry());
return attrs;
}
}
/**
* 统一错误处理
*/
@ControllerAdvice(basePackages = {"com.financial.manager.controller"})
public class ErrorControllerAdvice {
@ExceptionHandler(Exception.class)
@ResponseBody
public ResponseEntity handleException(Exception e){
Map<String, Object> attrs = new HashMap<>();
String errorCode = e.getMessage();
ErrorEnum errorEnum = ErrorEnum.getByCode(errorCode);
attrs.put("message",errorEnum.getMessage());
attrs.put("code",errorEnum.getCode());
attrs.put("canRetry",errorEnum.isCanRetry());
attrs.put("type","advice");
//Assert.isNull(attrs,"advice");
return new ResponseEntity(attrs, HttpStatus.INTERNAL_SERVER_ERROR);
}
}
public enum ErrorEnum {
ID_NOT_NULL("F001","编号不可为空",false),
//...
UNKNOWN("999","未知异常",false);
private String code;
private String message;
private boolean canRetry;
ErrorEnum(String code, String message, boolean canRetry) {
this.code = code;
this.message = message;
this.canRetry = canRetry;
}
public static ErrorEnum getByCode(String code){
for (ErrorEnum errorEnum : ErrorEnum.values()) {
if(errorEnum.code.equals(code)){
return errorEnum;
}
}
return UNKNOWN;
}
public String getCode() {
return code;
}
public String getMessage() {
return message;
}
public boolean isCanRetry() {
return canRetry;
}
}