Custom Error Objects for Spring Rest API And Authentication

前端 未结 1 678
盖世英雄少女心
盖世英雄少女心 2021-01-16 23:41

I have a spring boot rest API project and I am pondering how to change the default error object returned from spring boot.

UseCase: /token api is to be called witho

相关标签:
1条回答
  • 2021-01-16 23:51

    The exceptions from Servlet Filter which do not reach the controller are handled by BasicErrorController.

    You need to override the BasicErrorController to change the default exception body thrown by spring.

    How to override:

    @RestController
    @Slf4j
    public class BasicErrorControllerOverride extends AbstractErrorController {
    
      public BasicErrorControllerOverride(ErrorAttributes errorAttributes) {
        super(errorAttributes);
      }
    
      @RequestMapping
      public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {
        HttpStatus status = this.getStatus(request);
    
        /*
           If you want to pull default error attributes and modify them, use this
           Map<String, Object> defaultErrorAttributes = this.getErrorAttributes(request, false);
        */
    
        Map<String, Object> errorCustomAttribute = new HashMap<>();
        errorCustomAttribute.put("status", "error");
        errorCustomAttribute.put("message", status.name());
        return new ResponseEntity(errorCustomAttribute, status);
      }
    
      @Override
      public String getErrorPath() {
        return "/error";
      }
    }
    

    How error response will look like

    {
        "message": "UNAUTHORIZED",
        "status": "error"
    }
    
    0 讨论(0)
提交回复
热议问题