Java 在Spring中将自定义消息添加到@ExceptionHandler

Java 在Spring中将自定义消息添加到@ExceptionHandler,java,spring,exception,annotations,Java,Spring,Exception,Annotations,我想知道在抛出异常时如何从rest端点返回自定义状态代码和消息。下面的代码允许我在抛出UserDuplicateException时抛出自己的自定义状态代码571,但我似乎找不到一种方法来为其提供额外的消息或错误原因。你能帮忙吗 @ControllerAdvice public class ExceptionResolver { @ExceptionHandler(UserDuplicatedException.class) public void resolveAndWriteExcepti

我想知道在抛出异常时如何从rest端点返回自定义状态代码和消息。下面的代码允许我在抛出UserDuplicateException时抛出自己的自定义状态代码571,但我似乎找不到一种方法来为其提供额外的消息或错误原因。你能帮忙吗

@ControllerAdvice
public class ExceptionResolver {

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

}

您可以在响应中返回json,您可以使用它将对象转换为json,请尝试以下操作:

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);
}

这应该是直截了当的

创建自定义错误类:

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 
}

HttpServletResponse
有一个
senderro
方法,但它的javadoc中记录了其他含义。调查一下。
@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); 
    }
}