我想知道如何在抛出异常时从rest端点返回自定义状态代码和消息。下面的代码允许我在抛出UserDuplicatedException时抛出我自己的自定义状态代码571,但我似乎无法找到给它一个额外的消息或错误原因的方法。你能帮忙吗?
@ControllerAdvice
public class ExceptionResolver {
@ExceptionHandler(UserDuplicatedException.class)
public void resolveAndWriteException(Exception exception, HttpServletResponse response) throws IOException {
int status = 571;
response.setStatus(status);
}
}
答案 0 :(得分:1)
这应该是直截了当的。
创建自定义错误类:
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
}
在您的@ControllerAdvice
中
@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);
}
}
答案 1 :(得分:0)
你可以在响应中返回一个json,你可以使用Gson将一个对象转换为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);
}