在系统设计中,我们通常需要将自定义的异常以自定义的接口规范返回给客户端,以便进行统一的异常处理。
实现方式之ControllerAdvice
其中常用的一种方式是使用@RestControllerAdvice
来实现,代码如下:
/**
* 自定义的异常
*/
@Value
public class BizException extends RuntimeException {
private Integer errCode;
private String errMsg;
}
/**
* 异常处理
*/
@RestControllerAdvice
@Order(Ordered.HIGHEST_PRECEDENCE)
public class MyExceptionHandler {
@ExceptionHandler({BizException.class})
public Map<String, Object> handleClientException(BizException e) {
Map<String, Object> result = new HashMap<String, Object>(2);
result.put("errCode", result.getErrCode());
result.put("errMsg", result.getErrMsg());
return result;
}
}
实现方式之BasicErrorController
上述定义的ControllerAdvice
能够拦截并处理controller中抛出的异常,但是controller之外的则无法处理,但是可以通过修改Spring Boot中默认的异常处理BasicErrorController
来实现。
@Controller
@RequestMapping("${server.error.path:${error.path:/error}}")
public class MyErrorController extends BasicErrorController {
public MyErrorController(ErrorAttributes errorAttributes, ServerProperties serverProperties) {
super(errorAttributes, serverProperties.getError());
}
@Override
protected HttpStatus getStatus(HttpServletRequest request) {
// 修改HTTP响应码
return HttpStatus.OK;
}
@Override
protected Map<String, Object> getErrorAttributes(HttpServletRequest request, ErrorAttributeOptions options) {
// 修改返回的Body内容
Map<String, Object> errorAttributes = new LinkedHashMap<>();
errorAttributes.put("success", false);
errorAttributes.put("code", i);
errorAttributes.put("message", s);
return errorAttributes;
}
}