2017-11-10 111 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); 
} 
相關問題