2015-09-18 96 views
3

我用這個異常處理程序來處理我的春節,啓動應用程序(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狀態代碼在這種方法來處理錯誤信息等

問題

有一些方法如何將所有非處理的異常重定向到一個特定的方法是什麼?我該怎麼做?

+1

添加處理'Exception'的方法。最具體的將被選擇用於錯誤處理......並且簡單地添加'HttpServletRequest'和/或'HttpServletResponse'作爲方法參數。 –

回答

1

docs

在實現HandlerExceptionResolver將用於 攔截和處理在MVC系統引發的任何異常,而不是 由控制器進行處理DispatcherServlet會的申請 上下文中聲明任何Spring bean的。

public interface HandlerExceptionResolver { 
    ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex); 
} 
+0

我讀過這篇文章,但我不需要'ModelAndView',應該通過'@ ResponseBody'返回我的'ResponseMessage'。 – Artegon