SpringBoot中REST API的错误异常处理设计

https://www.jdon.com/49621

RESTful API中的异常Exception处理有两个基本要求,需要明确业务意义的错误消息以及hhtp状态码。良好的错误消息能够让API客户端纠正问题。在本文中,我们将讨论并实现Spring的REST API异常处理。

Restful API错误/异常设计
在RESTful API中设计异常处理时,最好在响应中设置HTTP状态代码,这样可以表示客户端的请求为什么会失败的原因。当然也可以发送更多信息包括HTTP状态码,这些将帮助客户端迅速定位错误。

比如下面是Springboot表示/api/producer不支持post方式的错误信息:

<span style="color:#333333">
{
    <span style="color:#00bb00">"timestamp"</span><span style="color:black">: 1530772698787,
    </span><span style="color:#00bb00">"status"</span><span style="color:black">: 405,
    </span><span style="color:#00bb00">"error"</span><span style="color:black">: </span><span style="color:#00bb00">"Method Not Allowed"</span><span style="color:black">,
    </span><span style="color:#00bb00">"exception"</span><span style="color:black">: </span><span style="color:#00bb00">"org.springframework.web.HttpRequestMethodNotSupportedException"</span><span style="color:black">,
    </span><span style="color:#00bb00">"message"</span><span style="color:black">: </span><span style="color:#00bb00">"Request method 'POST' not supported"</span><span style="color:black">,
    </span><span style="color:#00bb00">"path"</span><span style="color:black">: </span><span style="color:#00bb00">"/api/producer"</span>
<span style="color:black">}
</span></span>



对于我们的业务应用,应该提供更详细的有关业务的错误信息

<span style="color:#333333">
HTTP/1.1  404
Content-Type: application/json
{
    <span style="color:#00bb00">"status"</span><span style="color:black">: 404,
    </span><span style="color:#00bb00">"error_code"</span><span style="color:black">: 123,
    </span><span style="color:#00bb00">"message"</span><span style="color:black">: </span><span style="color:#00bb00">"Oops! It looks like that file does not exist."</span><span style="color:black">,
    </span><span style="color:#00bb00">"details"</span><span style="color:black">: </span><span style="color:#00bb00">"File resource does not exist.We are working on fixing this issue."</span><span style="color:black">,
    </span><span style="color:#00bb00">"information_link"</span><span style="color:black">: </span><span style="color:#00bb00">"/api/producer"</span>
<span style="color:black">}
</span></span>




在设计REST API的响应时,需要理解以下重点:

1. status表示HTTP状态代码。
2. error_code表示REST API特定的错误代码。此字段有助于传递API /业务领域中特定信息。比如类似Oracle错误ORA-12345
3. message字段表示人类可读的错误消息。国际化信息
4. details部分表示完整详细信息。
5. information_link字段指定有关错误或异常的详细信息的链接。


Spring REST错误处理
Spring和Spring Boot提供了许多错误/异常处理选项。比如 @ExceptionHandler注释,@ExceptionHandler是一个Spring注释,以处理请求引发的异常。此注释在@Controller级别上起作用。
 

<span style="color:#333333">
@RestController
<strong>public</strong> <strong>class</strong> WelcomeController {

    @GetMapping(<span style="color:#00bb00">"/greeting"</span><span style="color:black">)
    String greeting() throws Exception {
      </span><span style="color:#0000aa"><em>//</em></span>
<span style="color:black">    }

    @ExceptionHandler({Exception.<strong>class</strong>})
    <strong>public</strong>  handleException(){
       </span><span style="color:#0000aa"><em>//</em></span>
<span style="color:black">    }
}
</span></span>



该方法存在几个个问题或缺点:

(1)此注释仅对指定的控制器Controller有效。
(2)这个注释不是全局的,我们需要添加到每个控制器(不是很方便)。

大多数企业应用程序都是需要扩展Spring基类的控制器(也就是通用控制器)。我们可以将@ExceptionHandler加入基类控制器,来客服上面的不便和限制,但是有以下新问题:

(1)基类控制器不适用于所有类型的控制器。我们还是需要复制代码。
(2)程序员编写的控制器可能扩展不受我们控制的第三方面控制器类。

由于存在所有这些限制,因此建议不要在构建RESTful API时使用此方法



Spring的异常处理
Spring 3.2引入了@ControllerAdvice这个支持全局异常处理程序机制的注释。@ControllerAdvice可以让我们使用和上面完全相同的异常处理技术,但它是应用于整个应用程序,而不仅仅是某个控制器。看看下面的应用代码:
 

<span style="color:#333333">
@ControllerAdvice
<strong>public</strong> <strong>class</strong> GlobalRestExceptionHandler <strong>extends</strong> ResponseEntityExceptionHandler {

    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(Exception.<strong>class</strong>)
    <strong>public</strong> <strong>void</strong> defaultExceptionHandler() {
        <span style="color:#0000aa"><em>// Nothing to do</em></span>
<span style="color:black">    }
}
</span></span>



通过@ControllerAdvice和@ExceptionHandler组合,能够统一跨所有@RequestMapping方法实现集中式异常处理。这是在使用基于Spring的REST API时的一种便捷方式,因为可以指定ResponseEntity为返回值。

现在我们可以定义一下我们的错误类信息的代码,然后把这个对象嵌入ResponseEntity中返回。 
 

<span style="color:#333333">
<strong>public</strong> <strong>class</strong> ApiErrorResponse {

    <strong>private</strong> HttpStatus status;
    <strong>private</strong> String error_code;
    <strong>private</strong> String message;
    <strong>private</strong> String detail;
    
    <span style="color:#0000aa"><em>// getter and setters</em></span>
 <span style="color:#0000aa"><em>//Builder </em></span>
<span style="color:black">    <strong>public</strong> <strong>static</strong> <strong>final</strong> <strong>class</strong> ApiErrorResponseBuilder {
        <strong>private</strong> HttpStatus status;
        <strong>private</strong> String error_code;
        <strong>private</strong> String message;
        <strong>private</strong> String detail;

        <strong>private</strong> ApiErrorResponseBuilder() {
        }

        <strong>public</strong> <strong>static</strong> ApiErrorResponseBuilder anApiErrorResponse() {
            <strong>return</strong> <strong>new</strong> ApiErrorResponseBuilder();
        }

        <strong>public</strong> ApiErrorResponseBuilder withStatus(HttpStatus status) {
            <strong>this</strong>.status = status;
            <strong>return</strong> <strong>this</strong>;
        }

        <strong>public</strong> ApiErrorResponseBuilder withError_code(String error_code) {
            <strong>this</strong>.error_code = error_code;
            <strong>return</strong> <strong>this</strong>;
        }

        <strong>public</strong> ApiErrorResponseBuilder withMessage(String message) {
            <strong>this</strong>.message = message;
            <strong>return</strong> <strong>this</strong>;
        }

        <strong>public</strong> ApiErrorResponseBuilder withDetail(String detail) {
            <strong>this</strong>.detail = detail;
            <strong>return</strong> <strong>this</strong>;
        }

        <strong>public</strong> ApiErrorResponse build() {
            ApiErrorResponse apiErrorResponse = <strong>new</strong> ApiErrorResponse();
            apiErrorResponse.status = <strong>this</strong>.status;
            apiErrorResponse.error_code = <strong>this</strong>.error_code;
            apiErrorResponse.detail = <strong>this</strong>.detail;
            apiErrorResponse.message = <strong>this</strong>.message;
            <strong>return</strong> apiErrorResponse;
        }
    }
}
</span></span>




ApiErrorResponse类中每个字段的含义等同于前面JSON格式的错误信息含义。

下面我们看看几种常见的客户端请求错误场景下如何使用这个ApiErrorResponse类:

(1)当方法参数不是预期类型时,抛出MethodArgumentTypeMismatchException异常,我们构造ApiErrorResponse类嵌入ResponseEntity返回:
 

<span style="color:#333333">
@ExceptionHandler({MethodArgumentTypeMismatchException.<strong>class</strong>})
<strong>protected</strong> ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex, HttpHeaders headers, HttpStatus status, WebRequest request){

     ApiErrorResponse response =<strong>new</strong> ApiErrorResponse.ApiErrorResponseBuilder()
        .withStatus(status)
        .withError_code(status.BAD_REQUEST.name())
        .withMessage(ex.getLocalizedMessage()).build();

        <strong>return</strong> <strong>new</strong> ResponseEntity<>(response, response.getStatus());
    }
</span>




(2),当API无法读取HTTP消息时,抛出HttpMessageNotReadable异常
 

<span style="color:#333333">
 @ExceptionHandler({HttpMessageNotReadableException.<strong>class</strong>})
    <strong>protected</strong> ResponseEntity<Object> handleHttpMessageNotReadable(HttpMessageNotReadableException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
        String error = <span style="color:#00bb00">"Malformed JSON request "</span><span style="color:black">;
        ApiErrorResponse response = <strong>new</strong> ApiErrorResponse.ApiErrorResponseBuilder()
                .withStatus(status)
                .withError_code(</span><span style="color:#00bb00">"BAD_DATA"</span><span style="color:black">)
                .withMessage(ex.getLocalizedMessage())
                .withDetail(error + ex.getMessage()).build();
        <strong>return</strong> <strong>new</strong> ResponseEntity<>(response, response.getStatus());
    }
</span></span>



下面是我们可以看到REST调用的响应JSON:
 

<span style="color:#333333">
{
<span style="color:#00bb00">"status"</span><span style="color:black">: </span><span style="color:#00bb00">"BAD_REQUEST"</span><span style="color:black">,
</span><span style="color:#00bb00">"error_code"</span><span style="color:black">: </span><span style="color:#00bb00">"BAD_DATA"</span><span style="color:black">,
</span><span style="color:#00bb00">"message"</span><span style="color:black">: </span><span style="color:#00bb00">"JSON parse error: Unexpected character 
</span><span style="color:#00bb00">"detail"</span><span style="color:black">: </span><span style="color:#00bb00">"Malformed JSON request JSON parse error: Unexpected character ('<' (code 60)): expected a valid value (number, String, array, object, '<strong>true</strong>', 'false' or '<strong>null</strong>');
}
</span></span>




(3)处理自定义异常,将自定义异常返回给客户端API。

看一个简单的用例,当客户端API通过其唯一ID调用后端存储库查找记录时,如果找不到该记录,我们的存储库类会返回null或空对象,在这种情况下,即使找不到我们想要的资源记录,API也会向客户端返回http 200 (OK响应。 为了处理所有类似这样的情况,我们创建了一个自定义异常,并在全局异常处理器GlobalRestExceptionHandler中实现。
 

<span style="color:#333333">
@ExceptionHandler(CustomServiceException.<strong>class</strong>)
<strong>protected</strong> ResponseEntity<Object> handleCustomAPIException(HttpMessageNotReadableException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
  
   ApiErrorResponse response =<strong>new</strong> ApiErrorResponse.ApiErrorResponseBuilder()
         .withStatus(status)
         .withError_code(HttpStatus.NOT_FOUND.name())
         .withMessage(ex.getLocalizedMessage())
         .withDetail(ex.getMessage())
         .build();
        <strong>return</strong> <strong>new</strong> ResponseEntity<>(response, response.getStatus());
 }
</span>




这里不会详细介绍如何在REST API中处理一个个不同的异常,因为所有异常都可以按照上面方式进行类似方式处理。下面是REST API中一些常见异常的类可以提供参考:

HttpMediaTypeNotSupportedException
HttpRequestMethodNotSupportedException
TypeMismatchException


(4)默认异常处理程序
既然我们无法处理系统中的所有异常。那么我们可以创建一个fallback异常处理器来作为没有指定异常处理器的默认异常处理器。
 

<span style="color:#333333">
@ControllerAdvice
<strong>public</strong> <strong>class</strong> GlobalRestExceptionHandler <strong>extends</strong> ResponseEntityExceptionHandler {

    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(Exception.<strong>class</strong>)
    <strong>public</strong> <strong>void</strong> defaultExceptionHandler() {
        <span style="color:#0000aa"><em>// Nothing to do</em></span>
<span style="color:black">    }
}
</span></span>




Spring Boot REST异常处理
Spring Boot提供了许多构建RESTful API的功能。Spring Boot 1.4引入了@RestControllerAdvice注释,这样可以更容易地处理异常。它和用@ControllerAdvice和@ResponseBody一样方便:
 

<span style="color:#333333">
@RestControllerAdvice
<strong>public</strong> <strong>class</strong> RestExceptionHandler {

@ExceptionHandler(CustomNotFoundException.<strong>class</strong>)
<strong>public</strong> ApiErrorResponse handleNotFoundException(CustomNotFoundException ex) {

ApiErrorResponse response =<strong>new</strong> ApiErrorResponse.ApiErrorResponseBuilder()
      .withStatus(HttpStatus.NOT_FOUND)
      .withError_code(<span style="color:#00bb00">"NOT_FOUND"</span><span style="color:black">)
      .withMessage(ex.getLocalizedMessage()).build();
      
    <strong>return</strong> responseMsg;
    }
}
</span></span>



使用上述方法时,同时在Spring Boot的application.properties文件中将以下属性设置为true
 

<span style="color:#333333">
spring.mvc.<strong>throw</strong>-exception-<strong>if</strong>-no-handler-found=<strong>true</strong> 
# 如果处理一个请求发生异常没有异常处理器时,决定<span style="color:#00bb00">"NoHandlerFoundException"</span><span style="color:black">是否抛出 
</span></span>





概要
在Spring基础REST API中正确处理和处理异常非常重要。在这篇文章中,我们介绍了实现Spring REST异常处理的不同选项。

为REST API构建一个良好的异常处理工作流是一个迭代和复杂的过程。一个好的异常处理机制允许API客户端知道请求出了什么问题。

Error Handling for REST with Spring | Java Develop

猜你喜欢

转载自blog.csdn.net/qq_16605855/article/details/81476216