2017-11-10 102 views
0

我想知道如何在抛出异常时从休息端点返回自定义状态码和消息。下面的代码允许我在抛出UserDuplicatedException时抛出自己的自定义状态码571,但似乎无法找到一条给错误提供额外信息或原因的方法。你能帮忙吗?将自定义消息添加到Spring中的@ExceptionHandler中

@ControllerAdvice 
public class ExceptionResolver { 

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

}

+0

'HttpServletResponse'有一个'sendError'方法,但在它的Javadoc中记录其他影响。了解更多。 –

回答

0

这应该是直截了当。

创建自定义错误类:

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); 
    } 
} 
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); 
} 
相关问题