我用這個異常處理程序來處理我的春節,啓動應用程序(REST API)一些特定的例外:如何處理@ControllerAdvice中所有未處理的異常?
@ControllerAdvice
class GlobalExceptionHandler {
@ExceptionHandler(NotFoundException.class)
@ResponseStatus(HttpStatus.NOT_FOUND)
public
@ResponseBody
ResponseMessage notFound(NotFoundException ex) {
return new NotFoundResponseMessage(ex.getMessage());
}
@ResponseStatus(value = HttpStatus.UNSUPPORTED_MEDIA_TYPE)
@ExceptionHandler(HttpMediaTypeNotSupportedException.class)
public
@ResponseBody
ResponseMessage unsupportedMediaType(HttpMediaTypeNotSupportedException ex) {
return new UnsupportedMediaTypeResponseMessage(ex.getMessage());
}
@ExceptionHandler(UnauthorizedException.class)
@ResponseStatus(HttpStatus.UNAUTHORIZED)
public
@ResponseBody
ResponseMessage unauthorized(UnauthorizedException ex) {
return new UnauthorizedResponseMessage(ex.getMessage());
}
@ExceptionHandler(HttpRequestMethodNotSupportedException.class)
@ResponseStatus(HttpStatus.METHOD_NOT_ALLOWED)
public
@ResponseBody
ResponseMessage methodNotAllowed(HttpRequestMethodNotSupportedException ex) {
return new MethodNotAllowedResponseMessage(ex.getMessage());
}
@ExceptionHandler(ForbiddenException.class)
@ResponseStatus(HttpStatus.FORBIDDEN)
public
@ResponseBody
ResponseMessage forbidden(ForbiddenException ex) {
return new ForbiddenResponseMessage(ex.getMessage());
}
}
,我想處理所有其他異常與一個「全球性」的處理方法。但是,我需要得到HTTP狀態代碼在這種方法來處理錯誤信息等
問題
有一些方法如何將所有非處理的異常重定向到一個特定的方法是什麼?我該怎麼做?
添加處理'Exception'的方法。最具體的將被選擇用於錯誤處理......並且簡單地添加'HttpServletRequest'和/或'HttpServletResponse'作爲方法參數。 –