简体   繁体   English

如何更改 Spring Boot 错误响应中的状态代码?

[英]How to change Status code in spring boot error response?

I am making a simple rest service that makes some http calls and aggregates data using RestTemplate.我正在制作一个简单的休息服务,它使用 RestTemplate 进行一些 http 调用和聚合数据。

Sometimes i get NotFound error and sometimes BadRequest errors.有时我会收到 NotFound 错误,有时会收到 BadRequest 错误。

I want to respond with the same status code to my client and Spring seems to have this mapping out of the box.我想用相同的状态代码响应我的客户端,而 Spring 似乎具有开箱即用的映射。 the message is okay but the Status code is always 500 Internal Server error.消息没问题,但状态代码始终为 500 内部服务器错误。

I Would like to map my status code to the one i am initially receiving我想将我的状态代码映射到我最初收到的状态代码

    "timestamp": "2019-07-01T17:56:04.539+0000",
    "status": 500,
    "error": "Internal Server Error",
    "message": "400 Bad Request",
    "path": "/8b8a38a9-a290-4560-84f6-3d4466e8d7901"
}

i would like it to be this way我希望它是这样的

    "timestamp": "2019-07-01T17:56:04.539+0000",
    "status": 400,
    "error": "Internal Server Error",
    "message": "400 Bad Request",
    "path": "/8b8a38a9-a290-4560-84f6-3d4466e8d7901"
}

It throws HttpClientErrorException.BadRequest or HttpClientErrorException.NotFound它抛出 HttpClientErrorException.BadRequest 或 HttpClientErrorException.NotFound

my code is a simple endpoint :我的代码是一个简单的端点:

    @GetMapping("/{id}")
    public MyModel getInfo(@PathVariable String id){
        return MyService.getInfo(id);
    }

You can create global exception handling with @ControllerAdvice annotation.您可以使用@ControllerAdvice注释创建全局异常处理。 Like this:像这样:

@ControllerAdvice
public class RestResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {

    @ExceptionHandler(value = YourExceptionTypes.class)
    protected ResponseEntity<Object> handleBusinessException(RuntimeException exception, WebRequest request) {
        return handleExceptionInternal(exception, exception.getMessage(), new HttpHeaders(), HttpStatus.NOT_ACCEPTABLE, request);
    }
}

When an exception is thrown, the handler will catch and transform it to the desired response.当抛出异常时,处理程序将捕获并将其转换为所需的响应。 The original exception wont be propagated.原始异常不会被传播。

The accepted solution with the @ControllerAdvice is insufficient.接受的@ControllerAdvice解决方案是不够的。 That surely marks the response with the custom status code for the exception.这肯定会使用异常的自定义状态代码标记响应。 It does, however, not return the wanted response body as JSON but as only simple string - the message from the exception.但是,它不会将想要的响应主体作为 JSON 返回,而是作为简单的字符串返回 - 来自异常的消息。

To get the correct status code and the default error body the DefaultErrorAttributes can help.要获得正确的状态代码和默认错误正文, DefaultErrorAttributes可以提供帮助。

@ControllerAdvice
public class PackedTemplateNotRecodableExceptionControllerAdvice extends ResponseEntityExceptionHandler {
    @Autowired
    private DefaultErrorAttributes defaultErrorAttributes;

    @ExceptionHandler(PackedTemplateNotRecodableException.class)
    public ResponseEntity<Object> handlePackedTemplateNotRecodableException(final RuntimeException exception, final WebRequest webRequest) {
        // build the default error response
        webRequest.setAttribute(RequestDispatcher.ERROR_STATUS_CODE, HttpStatus.BAD_REQUEST.value(), RequestAttributes.SCOPE_REQUEST);
        final Map<String, Object> errorAttributes = defaultErrorAttributes.getErrorAttributes(webRequest, ErrorAttributeOptions.defaults());

        // return the error response with the specific response code
        return handleExceptionInternal(exception, errorAttributes, new HttpHeaders(), HttpStatus.BAD_REQUEST, webRequest);
    }
}

That way you'll receive the wanted error response, eg something like this:这样你会收到想要的错误响应,例如这样的:

{
    "timestamp": "2019-07-01T17:56:04.539+0000",
    "status": 400,
    "error": "Internal Server Error",
    "message": "400 Bad Request",
    "path": "/8b8a38a9-a290-4560-84f6-3d4466e8d7901"
}

I have spent a lot of time looking into this issue, including solutions from answers here, which didn't work for me (or I didn't implement correctly).我花了很多时间研究这个问题,包括这里答案的解决方案,这对我不起作用(或者我没有正确实施)。

I finally got a breakthrough.我终于有了突破。 Instead of throwing a generic Exception such as throw new Exception(message) , I created classes that extends the Exception class for the specific exception type - with their respective HTTP error codes and message我没有抛出诸如throw new Exception(message)类的通用异常,而是创建了扩展特定异常类型的Exception类的类 - 以及它们各自的 HTTP 错误代码和消息

@ResponseStatus(value = HttpStatus.BAD_REQUEST)
public class BadRequestException extends Exception{

    public BadRequestException(String message) {
       super(message);
    }
}

In your application logic, you can now throw the Bad Request exception with a message like so throw new BadRequestException("Invalid Email") .在您的应用程序逻辑中,您现在可以使用类似throw new BadRequestException("Invalid Email")的消息抛出 Bad Request 异常。 This will result in an exception thrown thus :这将导致抛出异常,因此:

{
"timestamp": "2021-03-01T17:56:04.539+0000",
"status": 400,
"error": "Bad Request",
"message": "Invalid Email",
"path": "path to controller"
}

You can now create other custom exception classes for the different exceptions you want, following the above example and changing the value parameter in the @ResponseStatus, to match the desired response code you want.您现在可以按照上述示例并更改 @ResponseStatus 中的 value 参数,为所需的不同异常创建其他自定义异常类,以匹配所需的响应代码。 eg for a NOT FOUND exception @ResponseStatus (value = HttpStatus.NOT_FOUND) , Java provides the different HTTP status codes via the HttpStatus enum.例如,对于 NOT FOUND 异常@ResponseStatus (value = HttpStatus.NOT_FOUND) ,Java 通过HttpStatus枚举提供不同的 HTTP 状态代码。

For more context更多上下文

I hope this is detailed enough and helps someone :)我希望这足够详细并且可以帮助某人:)

Spring Resttemplate 异常处理的可能重复您的代码需要一个控制器通知来处理来自它正在调用的服务的异常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Spring Boot和安全性:如何扩展302状态代码的响应? - Spring Boot and security: How to extend response for 302 status code? 如何使用 Boot 仅更改 Spring MVC 错误上的状态代码? - How do I change only the status code on a Spring MVC error with Boot? Spring 3.2 DeferredResult - 如何设置错误响应的状态代码? - Spring 3.2 DeferredResult - How to set status code for error response? 在不更改错误响应正文或状态代码的情况下记录 Spring 引导 controller 异常 - Log Spring Boot controller exceptions without changing the error response body or status code Spring 带有响应状态代码的 MVC 错误处理 - Spring MVC error handling with response status code 在 Spring Boot 中返回状态码为 202 的 HTTP 响应 - Return HTTP response with status code 202 in Spring Boot Spring Security:如何更改响应的 HTTP 状态? - Spring Security: how to change HTTP Status for response? Spring Boot返回200个自定义错误页面的状态代码 - Spring boot returning 200 status code for custom error pages 自定义 Spring 开机报错响应码不改默认正文 - Customize Spring Boot error response code without changing the default body 预检响应在Angle 4和Spring Boot(RestAPI)应用程序中具有无效的HTTP状态代码403 - Response for preflight has invalid HTTP status code 403 in angular 4 & spring boot (RestAPI) application
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM