Spring Boot、Spring Cloud支持多种统一管理异常的方式,例如:
- 继承
org.springframework.boot.autoconfigure.web.BasicErrorController
ExceptionHandler
Spring Cloud YES中使用的是继承BasicErrorController
的方式,好处在于,使用这种方案,无需自己判断某个API是否AJax接口。示例代码如下:
@Controller
@RequestMapping("/error")
public class MyErrorController extends BasicErrorController {
@Autowired
public MyErrorController(ErrorAttributes errorAttributes, ServerProperties serverProperties) {
super(errorAttributes, serverProperties.getError());
}
@RequestMapping(produces = "text/html")
@Override
public ModelAndView errorHtml(HttpServletRequest request,
HttpServletResponse response) {
return super.errorHtml(request, response);
}
@RequestMapping
@ResponseBody
@Override
@SuppressWarnings("unchecked")
public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {
Map<String, Object> body = super.getErrorAttributes(request,
isIncludeStackTrace(request, MediaType.ALL));
String message = body.get("message") != null ? (String) body.get("message") : null;
Integer statusCode = body.get("status") != null ? (Integer) body.get("status") : null;
Object exception = body.get("exception");
if (exception != null && exception instanceof BizRuntimeException) {
BizRuntimeException bre = (BizRuntimeException) exception;
statusCode = bre.getCode();
}
AjaxResult<Object> build = AjaxResult.builder()
.status(statusCode)
.error(message)
.message(message)
.data(body)
.build();
Map res = null;
try {
ObjectMapper mapper = new ObjectMapper();
String s = mapper.writeValueAsString(build);
res = mapper.readValue(s, Map.class);
} catch (IOException e) {
e.printStackTrace();
}
HttpStatus status = super.getStatus(request);
return new ResponseEntity<Map<String, Object>>(res, status);
}
}