簡體   English   中英

Spring MVC通用異常處理

[英]Spring MVC Generic Exception Handling

我正在使用以下通用類來處理我的應用程序中的所有類型的異常。 它處理大多數異常,但對於某些異常,例如“ org.apache.tiles.impl.CannotRenderException”,則無法處理。 如何使其捕獲所有類型的異常?

我正在使用的一些技術是:Spring 4.0.0.RELEASE,Tiles 2.2,Maven 1.6,Spring Webflow 2.4.0.RELEAS

@ControllerAdvice
class GenericDefaultExceptionHandler {
    public static final String DEFAULT_ERROR_VIEW = "error/error";
    private static final String DEFAULT_ERROR_SUBJECT = "Exception occurred";
    final Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private MailService mailService;

    @ExceptionHandler(value = Exception.class)
    public ModelAndView defaultErrorHandler(HttpServletRequest req, Exception e) throws Exception {
        if (AnnotationUtils.findAnnotation(e.getClass(), ResponseStatus.class) != null)
            throw e;
        ModelAndView mav = new ModelAndView();
        mav.addObject("exception", e);
        mav.addObject("url", req.getRequestURL());
        mav.setViewName(DEFAULT_ERROR_VIEW);
        //send email to system admin
        sendMessageToAdmin(e.toString(),req.getRequestURL().toString());
        logger.error(e.toString());
        return mav;
    }

    private void sendMessageToAdmin(String exceptionAsMessage, String url) {
        try {
            StringBuilder errorMessage = new StringBuilder();
            errorMessage.append("Exception on request URL :");
            errorMessage.append(url);
            errorMessage.append("\n\n");
            errorMessage.append("The Exception was: ");
            errorMessage.append(exceptionAsMessage);
            mailService.sendMailWithSubject(DEFAULT_ERROR_SUBJECT,errorMessage.toString());
        } catch (Exception e) {

        }
    }
}

謝謝

問題是您的處理程序在控制器中捕獲了異常,但是在控制器完成其工作后,在視圖中引發了平鋪異常。 您可以嘗試使用過濾器來處理它們:

public void doFilter(ServletRequest request, ServletResponse response,
        FilterChain chain) throws IOException, ServletException {
    ...
    try {
        chain.doFilter(request, response);
    }
    catch (Exception ex) {
        // your stuff
        ...
        throw new ServletException(ex);
    }
}

獨立於此(或除此之外),您還可以要求容器在發現異常時或控制器在web.xml文件中使用具有某些配置的sendError時使用一些視圖:

<!-- error-code related error pages -->
<error-page>
    <error-code>404</error-code>
    <location>/ErrorHandler</location>
</error-page>
<error-page>
    <error-code>403</error-code>
    <location>/ErrorHandler</location>
</error-page>

<!-- exception-type related error pages -->
<error-page>
    <exception-type>
          javax.servlet.ServletException
    </exception-type >
    <location>/ErrorHandler</location>
</error-page>

<error-page>
    <exception-type>java.io.IOException</exception-type >
    <location>/ErrorHandler</location>
</error-page>

是的,篩選器為我工作。 我創建了一個擴展Spring過濾器的GenericFilterBean的異常類,並將其注冊到我的ApplicationConfig中。

public class ApplicationConfig implements WebApplicationInitializer {
    .....
    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        .....
        FilterRegistration.Dynamic exception = servletContext.addFilter("genericExceptionFilter", new GenericExceptionFilter());
        exception.addMappingForUrlPatterns(dispatcherTypes, true, "/*");
        .....
    }
}

謝謝。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM