简体   繁体   中英

Adding a custom message to a @ExceptionHandler in Spring

I was wondering how it is possible to return a custom status code and message from a rest endpoint when throwing an exception. The code below allows me to throw my own, custom status code 571 when UserDuplicatedException is thrown, but I cant seem to fnd a way to give it an additional message or reason for the error. Can you help please?

@ControllerAdvice
public class ExceptionResolver {

@ExceptionHandler(UserDuplicatedException.class)
public void resolveAndWriteException(Exception exception, HttpServletResponse response) throws IOException {
    int status = 571;
    response.setStatus(status);
}

}

This should be straight forward.

Create custom error class:

public class Error {
    private String statusCode;
    private String message;
    private List<String> errors;
    private Date date;

    public Error(String status, String message) {
        this.statusCode = status;
        this.message = message;
    }

    //Getters - Setters 
}

And in your @ControllerAdvice as

@ControllerAdvice
public class ExceptionResolver {

    @ExceptionHandler(UserDuplicatedException.class)
    public ResponseEntity<Error> resolveAndWriteException(UserDuplicatedException e) throws IOException {
        Error error = new Error("571", e.getMessage());
        error.setErrors(//get your list or errors here...);
        return new ResponseEntity<Error>(error, HttpStatus.Select-Appropriate); 
    }
}

you will can return a json in the response, yo can use Gson for transform a object to JSON, please try this:

public class Response{
   private Integer status;
   private String message;

   public String getMessage(){
      return message;
   }

   public void setMessage(String message){
     this.message = message;
   }

   public Integer getStatus(){
      return status;
   }

   public Integer setStatus(Integer status){
      this.status = status;
   }
}    

@ExceptionHandler(UserDuplicatedException.class)
@ResponseBody
public String resolveAndWriteException(Exception exception) throws IOException {
    Response response = new Response();
    int status = 571;
    response.setStatus(571);
    response.setMessage("Set here the additional message");
    Gson gson = new Gson();
    return gson.toJson(response);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM