Spring Boot对异常的处理有一套默认的机制:当应用中产生异常时,Spring Boot根据发送请求头中的accept是否包含text/html来分别返回不同的响应信息。当从浏览器地址栏中访问应用接口时,请求头中的accept便会包含text/html信息,产生异常时,Spring Boot通过org.springframework.web.servlet.ModelAndView对象来装载异常信息,并以HTML的格式返回;而当从客户端访问应用接口产生异常时(客户端访问时,请求头中的accept不包含text/html),Spring Boot则以JSON的格式返回异常信息。下面来验证一下。

默认异常处理机制

假设应用中有如下一个Controller:

  1. @RestController
  2. @RequestMapping("user")
  3. public class UserController {
  4. @GetMapping("/{id:\\d+}") //必须为数字
  5. public void get(@PathVariable String id) {
  6. throw new RuntimeException("user not exist");
  7. }
  8. }

在代码中我们主动的抛出了一个RuntimeException,先打开浏览器的开发者模式,再使用浏览器访问http://localhost:8080/user/1Spring Boot异常处理 - 图1可看到页面返回了一些异常描述,并且请求头的accpet包含了text/html片段。

接着使用模拟发送REST请求的Chrome插件Restlet Client发送http://localhost:8080/user/1

Spring Boot异常处理 - 图2

可以看到请求头的accept值为*/*,并且返回一段JSON格式的信息。

或者使用Postman:
Screen Shot 2021-11-13 at 3.21.33 PM.png

查看Spring Boot的BasicErrorController类便可看到这一默认机制的具体实现:

Spring Boot异常处理 - 图4

可看到errorHtmlerror方法的请求地址和方法是一样的,唯一的区别就是errorHtml通过produces = {"text/html"}判断请求头的accpet属性中是否包含text/html,如果包含,便走该方法。

自定义html异常页面

我们可以通过在src/main/resources/resources/error路径下定义友好的异常页面,比如定义一个500.html页面:

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>500</title>
  6. </head>
  7. <body>
  8. 系统内部异常
  9. </body>
  10. </html>

然后再次通过浏览器访问:http://localhost:8080/user/1:

Spring Boot异常处理 - 图5

同样的,我们也可以定义404.html等常见的HTTP状态码对应的异常页面。

通过自定义html异常页面并不会影响客户端发送请求异常返回的结果。

自定义异常处理

参考:springboot优雅实现异常处理

除了可以通过自定义html异常页面来改变浏览器访问接口时产生的异常信息,我们也可以自定义异常处理来改表默认的客户端访问接口产生的异常信息。

我们手动定义一个UserNotExistException,继承RuntimeException

  1. public class UserNotExistException extends RuntimeException{
  2. private static final long serialVersionUID = -1574716826948451793L;
  3. private String id;
  4. public UserNotExistException(String id){
  5. super("user not exist");
  6. this.id = id;
  7. }
  8. public String getId() {
  9. return id;
  10. }
  11. public void setId(String id) {
  12. this.id = id;
  13. }
  14. }

然后定义一个Controller异常处理类ControllerExceptionHandler

  1. @ControllerAdvice
  2. public class ControllerExceptionHandler {
  3. @ExceptionHandler(UserNotExistException.class)
  4. @ResponseBody
  5. @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
  6. public Map<String, Object> handleUserNotExistsException(UserNotExistException e) {
  7. Map<String, Object> map = new HashMap<>();
  8. map.put("id", e.getId());
  9. map.put("message", e.getMessage());
  10. return map;
  11. }
  12. }

其中注解@ExceptionHandler指定了要处理的异常类型,注解@ResponseStatus指定异常处理方法返回的HTTP状态码为HttpStatus.INTERNAL_SERVER_ERROR,即500。HttpStatus是一个spring自带的枚举类型,封装了常见的HTTP状态码及描述:

  1. public enum HttpStatus {
  2. CONTINUE(100, "Continue"),
  3. SWITCHING_PROTOCOLS(101, "Switching Protocols"),
  4. PROCESSING(102, "Processing"),
  5. CHECKPOINT(103, "Checkpoint"),
  6. OK(200, "OK"),
  7. CREATED(201, "Created"),
  8. ACCEPTED(202, "Accepted"),
  9. NON_AUTHORITATIVE_INFORMATION(203, "Non-Authoritative Information"),
  10. NO_CONTENT(204, "No Content"),
  11. RESET_CONTENT(205, "Reset Content"),
  12. PARTIAL_CONTENT(206, "Partial Content"),
  13. MULTI_STATUS(207, "Multi-Status"),
  14. ALREADY_REPORTED(208, "Already Reported"),
  15. IM_USED(226, "IM Used"),
  16. MULTIPLE_CHOICES(300, "Multiple Choices"),
  17. MOVED_PERMANENTLY(301, "Moved Permanently"),
  18. FOUND(302, "Found"),
  19. /** @deprecated */
  20. @Deprecated
  21. MOVED_TEMPORARILY(302, "Moved Temporarily"),
  22. SEE_OTHER(303, "See Other"),
  23. NOT_MODIFIED(304, "Not Modified"),
  24. /** @deprecated */
  25. @Deprecated
  26. USE_PROXY(305, "Use Proxy"),
  27. TEMPORARY_REDIRECT(307, "Temporary Redirect"),
  28. PERMANENT_REDIRECT(308, "Permanent Redirect"),
  29. BAD_REQUEST(400, "Bad Request"),
  30. UNAUTHORIZED(401, "Unauthorized"),
  31. PAYMENT_REQUIRED(402, "Payment Required"),
  32. FORBIDDEN(403, "Forbidden"),
  33. NOT_FOUND(404, "Not Found"),
  34. METHOD_NOT_ALLOWED(405, "Method Not Allowed"),
  35. NOT_ACCEPTABLE(406, "Not Acceptable"),
  36. PROXY_AUTHENTICATION_REQUIRED(407, "Proxy Authentication Required"),
  37. REQUEST_TIMEOUT(408, "Request Timeout"),
  38. CONFLICT(409, "Conflict"),
  39. GONE(410, "Gone"),
  40. LENGTH_REQUIRED(411, "Length Required"),
  41. PRECONDITION_FAILED(412, "Precondition Failed"),
  42. PAYLOAD_TOO_LARGE(413, "Payload Too Large"),
  43. /** @deprecated */
  44. @Deprecated
  45. REQUEST_ENTITY_TOO_LARGE(413, "Request Entity Too Large"),
  46. URI_TOO_LONG(414, "URI Too Long"),
  47. /** @deprecated */
  48. @Deprecated
  49. REQUEST_URI_TOO_LONG(414, "Request-URI Too Long"),
  50. UNSUPPORTED_MEDIA_TYPE(415, "Unsupported Media Type"),
  51. REQUESTED_RANGE_NOT_SATISFIABLE(416, "Requested range not satisfiable"),
  52. EXPECTATION_FAILED(417, "Expectation Failed"),
  53. I_AM_A_TEAPOT(418, "I'm a teapot"),
  54. /** @deprecated */
  55. @Deprecated
  56. INSUFFICIENT_SPACE_ON_RESOURCE(419, "Insufficient Space On Resource"),
  57. /** @deprecated */
  58. @Deprecated
  59. METHOD_FAILURE(420, "Method Failure"),
  60. /** @deprecated */
  61. @Deprecated
  62. DESTINATION_LOCKED(421, "Destination Locked"),
  63. UNPROCESSABLE_ENTITY(422, "Unprocessable Entity"),
  64. LOCKED(423, "Locked"),
  65. FAILED_DEPENDENCY(424, "Failed Dependency"),
  66. UPGRADE_REQUIRED(426, "Upgrade Required"),
  67. PRECONDITION_REQUIRED(428, "Precondition Required"),
  68. TOO_MANY_REQUESTS(429, "Too Many Requests"),
  69. REQUEST_HEADER_FIELDS_TOO_LARGE(431, "Request Header Fields Too Large"),
  70. UNAVAILABLE_FOR_LEGAL_REASONS(451, "Unavailable For Legal Reasons"),
  71. INTERNAL_SERVER_ERROR(500, "Internal Server Error"),
  72. NOT_IMPLEMENTED(501, "Not Implemented"),
  73. BAD_GATEWAY(502, "Bad Gateway"),
  74. SERVICE_UNAVAILABLE(503, "Service Unavailable"),
  75. GATEWAY_TIMEOUT(504, "Gateway Timeout"),
  76. HTTP_VERSION_NOT_SUPPORTED(505, "HTTP Version not supported"),
  77. VARIANT_ALSO_NEGOTIATES(506, "Variant Also Negotiates"),
  78. INSUFFICIENT_STORAGE(507, "Insufficient Storage"),
  79. LOOP_DETECTED(508, "Loop Detected"),
  80. BANDWIDTH_LIMIT_EXCEEDED(509, "Bandwidth Limit Exceeded"),
  81. NOT_EXTENDED(510, "Not Extended"),
  82. NETWORK_AUTHENTICATION_REQUIRED(511, "Network Authentication Required");
  83. ...
  84. }

编写完自定义异常处理逻辑后,我们将UserController中的方法抛出的异常改为UserNotExistException

  1. @GetMapping("/{id:\\d+}")
  2. public void get(@PathVariable String id) {
  3. throw new UserNotExistException(id);
  4. }

重启项目,使用Restlet Client再次访问http://localhost:8080/user/1,响应如下:Spring Boot异常处理 - 图6
网页访问一样结果:
Screen Shot 2021-11-13 at 3.34.10 PM.png