How to throw an exception back in JSON in Spring Boot

前端 未结 6 1298
-上瘾入骨i
-上瘾入骨i 2020-12-29 09:11

I have a Request Mapping -

  @RequestMapping(\"/fetchErrorMessages\")
  public @ResponseBody int fetchErrorMessages(@RequestParam(\"startTime\") String star         


        
6条回答
  •  旧时难觅i
    2020-12-29 09:37

    This is how I did it in my application:

    import org.springframework.web.bind.annotation.ControllerAdvice;
    import org.springframework.web.bind.annotation.ExceptionHandler;
    
    @ControllerAdvice
    public class ExceptionHandlingControllerAdvice {
    
       @ExceptionHandler(ExecutionRestrictionViolationException.class)
       public ResponseEntity handleExecutionRestrictionViolationException(ExecutionRestrictionViolationException ex) {
         return response("Invalid Query", ex.getMessage(), HttpStatus.UNPROCESSABLE_ENTITY);
       }
    
       private static String createJson(String message, String reason) {
        return "{\"error\" : \"" + message + "\"," +
                "\"reason\" : \"" + reason  + "\"}";
       }
    
       private static ResponseEntity response(String message,
                                                   String reason,
                                                   HttpStatus httpStatus) {
        String json = createJson(message, reason);
        return new ResponseEntity<>(json, httpStatus);
       }
    
    }
    

    Explanation:

    1. You create a controller Advice, mark it with a special annotation and define just like any other bean (in my case it was a java configuration, but it doesn't really matter)

    2. For each Exception you would like to handle like this - define a handler that will generate a response in a format you want

    3. There is a static method createJson - you can use a different way, it also doesn't matter really.

    Now this is only one way to work (its available in more recent spring boot versions) - but there are others:

    All the methods I'm aware of (and even more) are listed here.

提交回复
热议问题