【问题标题】:how to get access to the default spring error JSON如何访问默认的 spring 错误 JSON
【发布时间】:2020-08-07 03:50:22
【问题描述】:

似乎默认情况下 Spring 会返回一条消息:

{
    "timestamp": "2019-01-17T16:12:45.977+0000",
    "status": 500,
    "error": "Internal Server Error",
    "message": "Error processing the request!",
    "path": "/my-endpoint-with-exceptions"
}

目前,该应用程序在每个异常上都使用带有 @ExceptionHandler 的 @RestControllerAdvice。在每个方法中它使用一个 ResponseEntity

@ExceptionHandler(GenericException.class)
public ResponseEntity<String> exceptionHandler(GenericException ex){
 return new ResponseEntity<>(ex.getMessage,HttpStatus.BAD_REQUEST)
}

此外,随着时间的推移,似乎已经有许多类与默认使用的时间大致相同。

所以宁愿使用默认的 Spring JSON 但是当然不想影响当前正在运行的代码。所以我的问题是只让 GenericException 返回默认的 Spring JSON?

我确实尝试使用 ResponseStatusException,它确实返回了 JSON,但无论出于何种原因,即使在参数中设置值,也只会返回 INTERNAL_SERVER_ERROR (500) 状态。

【问题讨论】:

    标签: spring spring-boot


    【解决方案1】:

    您可以定义自己的错误响应并从异常处理程序方法中返回它。 像这样的:

    型号:

    @Builder
    public class ErrorResponse {
    
        private int status;
    
        private String error;
    
        private String message;
    
        private String path;
    
        private long timestamp;
    }
    

    处理程序:

    @ExceptionHandler(GenericException.class)
    public ResponseEntity<ErrorResponse> exceptionHandler(GenericException ex){
        ErrorResponse errorResponse = ErrorResponse.builder()
            .message(ex.getMessage())
            .status(HttpStatus.BAD_REQUEST.value())
            .error(HttpStatus.BAD_REQUEST.getReasonPhrase())
            .build();
    
        return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
    }
    

    【讨论】:

    • 是的,我确实尝试过,而且肯定会奏效。但有点惊讶,去春季赛这么痛苦
    • 是的,我遇到了同样的问题,我发现我只能自定义消息。但我认为这个选项看起来不错。
    猜你喜欢
    • 2021-10-08
    • 1970-01-01
    • 2019-09-26
    • 2017-03-08
    • 1970-01-01
    • 2015-10-06
    • 2012-04-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多