简体   繁体   English

响应实体<errorresponse>没有作为自定义 HTTP 响应正文返回</errorresponse>

[英]ResponseEntity<ErrorResponse> not getting returned as custom HTTP response body

ErrorResponse class:错误响应 class:

public class ErrorResponse {
    private String errorCode;
    private String errorMessage;
    ...
}

Controller Advice: Controller 建议:

@ExceptionHandler(BaseException.class)
    public ResponseEntity<Object> handleBaseException(BaseException exception) {
        ErrorResponse res = new ErrorResponse(exception.getErrorCode().toString(),exception.getMessage());
        return new ResponseEntity<>(res, HttpStatus.NOT_FOUND);
    }

Http response: Http 响应:

{
    "timestamp": 1661865968618,
    "status": 500,
    "error": "Internal Server Error",
    "message": "custom message",
    "path": "...."
}

Expected Http response:预期的 Http 响应:

{
    "errorCode": "...",
    "errorMessage": "..."
}

Can anyone help me with the return statement of @controlleradvice such that I can get the expected Http response?任何人都可以帮助我处理@controlleradvice 的返回语句,以便我可以获得预期的 Http 响应吗?

@ExceptionHandler(BaseException.class)
    public ResponseEntity<?> handleBaseException(HttpServletRequest request, BaseException exception) {
    return ResponseEntity
    .status(HttpStatus.NOT_FOUND)
    .body(new ErrorResponse(HttpStatus.NOT_FOUND, exception.getMessage()), String.valueOf(request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE)));
)

暂无
暂无

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

相关问题 即使使用HttpStatus.BAD_REQUEST返回ResponseEntity,也要在API响应中获取HTTP响应代码200 - Getting HTTP response code 200 in API response even after returning ResponseEntity with HttpStatus.BAD_REQUEST 返回ResponseEntity和Http错误时,RestTemplate.postForObject返回Null - RestTemplate.postForObject Returns Null When ResponseEntity and Http Error Are Returned Spring HTTP出站网关-如何返回带有主体的ResponseEntity - Spring http outbound gateway - how to return a ResponseEntity with a body “缺少所需的请求正文:public org.springframework.http.ResponseEntity<?> - "Required request body is missing: public org.springframework.http.ResponseEntity<?> Spring-使用HttpEntity从ResponseEntity获取主体的通用方法 - Spring - generic method for getting body from ResponseEntity using HttpEntity 播放2.5:在自定义http操作中获取响应正文 - Play 2.5: get response body in custom http action 播放2.6:在自定义http操作中获取响应正文 - Play 2.6: get response body in custom http action 在响应中,当将通量返回为 ResponseEntity 时,我得到 scanAvailable=true - In the Response, i am getting scanAvailable=true when returning flux as ResponseEntity 如何模拟服务 class 调用 Rest API 并将 ResponseEntity 作为响应 - How to mock a service class calling Rest API and getting ResponseEntity as Response 如何在 Spring Boot Rest api 响应的 ResponseEntity 中添加自定义属性 - How to add custom attributes in ResponseEntity of Spring Boot Rest api response
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM