如何在Spring MVC中使用自定义拦截器处理自定义异常?

时间:2018-09-11 13:18:01

标签: spring-mvc

我有一个问题,尽管我在try catch块中添加了代码并创建了一个自定义拦截器,但我无法处理自定义异常,但我找不到如何拦截异常的方法,我必须处理用户定义的异常(例如sql异常)表不存在,还必须在屏幕上显示错误消息。

我有这个拦截器处理程序类:

public class RNTExceptionInterceptor implements ThrowsAdvice{

    /** Creating instance of the Log class for logging the errors. */

    private static final Logger log = LogManager.getLogger(RNTExceptionInterceptor.class);
    /**
     * This method is used to generate log on each target objects method's exception and set the error code for
     * 
     * @param method Method object
     * @param args set of arguments
     * @param target Target class
     * @param ex Error Object
     * @throws RNTSystemException when any system related exception occurs
     * @throws RNTBusinessException when any business related exception occurs
     */
    public void afterThrowing(Method method, Object[] args, Object target, Throwable ex)
            throws RNTSystemException, RNTBusinessException {

        log.error("Exception in method: " + method.getName() + " Exception is: " + ex.getMessage(), ex);
        log.info(getStackTrace(ex));
        log.info("Class of the exception is "+ex.getClass());



        if (ex instanceof RNTBusinessException) {
            throw (RNTBusinessException)ex;

        } else if (ex instanceof RNTSystemException) {
            throw (RNTSystemException)ex;

        } else if (ex instanceof NullPointerException) {
            throw new RNTSystemException(SYSTEM_ERROR, ex);

        } else {
            throw new RNTSystemException(ex.getMessage(), ex);
        }
    }

这是我的控制器:

@RequestMapping(value = "/displayKra.do")
    public ModelAndView displayKra(HttpServletRequest request, HttpServletResponse res) throws RNTException,SQLException, PropertyVetoException{

        HttpSession session = request.getSession();
        Dashboard dashboard = (Dashboard) session.getAttribute(DASHBOARD_SESSION_ATTRIBUTE);
        AppraisalType appraisaltype=null;

        try{
            appraisaltype = appraisalDao.getManagerList(dashboard.getStaffID());
            appraisaltype.setUserMessage(getMessage(MANAGER_LIST_FETCHED_SUCCESSFULLY));
        }catch(RNTSystemException e){
                log.error(e.getMessage(),e);
                appraisaltype.setErrorMessage(e.getMessage());
        }
        return new ModelAndView(KRA_1_JSP, "appraisaltype", appraisaltype);
    }

0 个答案:

没有答案
相关问题