Java的异常捕获该怎么写?

各位大大好.

问题如下:

我在写一个Spring mvc项目, 在dao层类中写了一个可能会执行失败的方法:

 

/**
 * 删除
 */
public void remove(int id) throws Exception {
    Session session = getSession();
    session.delete(session.load(Usergroup.class, id));
}

 

这个方法删除的记录可能跟别的表有外键关联,所以可能删除失败.

然后我在service层的类中调用它:

 

    /**
     * 删除
     */
    public Map<String, Object> remove(int id) {
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            userGroupDao.remove(id);
            map.put("isSuccess", true);
        } catch (Exception e) {
            map.put("isSuccess", false);
            map.put("errorMsg", e.getMessage());
        }
        return map;
    }

 

我希望在service层调用这个方法时,如果失败就给返回值map加入错误信息, 然后 前端页面 显示错误,
而不是 显示Tomcat的

HTTP Status 500 -

type Exception report

这个画面.


请问怎么实现?

谢谢大大们!!!

思想就是dao抛出异常,service接着抛出,controller也不要管,一直到ExceptionResolver进行拦截,然后返回错误信息就可以了。

在请求action中获取map的值,如果是 isSuccess false 就跳入错误页面这个可以在web.xml中配置错误页面当然map可以存放错误信息,这个错误信息可以在 配置的500错误页面中显示出来
web.xml


500

/error.jsp



希望能帮上忙

你的友好错误页面,可以交给容器来完成。web.xml
来配置。而不要把错误的细节告诉给用户。

错误应该通过日志记录到日志文件中。可以借助log4j这样的工具包。

另外除了错误信息可以封闭一下,明确哪个类哪个方法,什么样的错误。还是建议用log4j这类的现成工具包。

我们在项目中的处理,可以定义一个ExceptionResolver,然后在这个里面将e.getMessage信息拿出来就可以了,这个里面可以判断是ajax请求还是普通的请求,可以返回到不同的地方,欢迎讨论。

[code="java"]
public class MappingExceptionResolver extends SimpleMappingExceptionResolver {

private String getErrorMsg(Exception e){
    String errorMsg = "";
    Throwable cause = e.getCause();
    if(cause != null && StringUtils.isNotBlank(cause.getMessage())){
        errorMsg = e.getCause().getMessage();
    } else if(StringUtils.isNotBlank(e.getMessage())){
        errorMsg = e.getMessage();
    } 
    return errorMsg;
}

@Override
protected ModelAndView doResolveException(HttpServletRequest request,
        HttpServletResponse response, Object handler, Exception ex) {       
    String accept = request.getHeader("accept");
    if(accept.indexOf("application/json")>-1){
        Map<String,String> errors = new HashMap<String,String>();
        errors.put("errorCode", "-1");
        errors.put("errorMsg", getErrorMsg(ex));

        request.setAttribute("errorJson", JSONObject.fromObject(errors).toString());
        return super.getModelAndView("errors/ajax/500", ex, request);
    }
    if (ex instanceof TnAccessDeniedException) {
        response.setStatus(HttpStatus.SC_FORBIDDEN);            
    }
    return super.doResolveException(request, response, handler, ex);
}

protected ModelAndView getModelAndView(String viewName, Exception ex) {
    if(ex instanceof TnBaseException){
        LoggerHelper.err(MappingExceptionResolver.class,ex.getMessage());
    }else{
        LoggerHelper.err(MappingExceptionResolver.class,"", ex);
    }
    return super.getModelAndView(viewName, ex);
}

}
[/code]

ExceptionResolver的配置如下:

[code="xml"]

<bean id="exceptionResolver" class="com.ddd.xxxx.common.web.MappingExceptionResolver">
    <property name="defaultErrorView" value="errors/500" />
    <property name="exceptionMappings">
        <props>
            <prop key="com.ddd.exception.UnhandledViewException">errors/unhandledView</prop>
            <prop key="org.springframework.security.access.AccessDeniedException">errors/403</prop>
            <prop key="com.ddd.xxx.common.exception.TnAccessDeniedException">errors/403</prop>
            <prop key="java.lang.Exception">errors/500</prop>
        </props>
    </property>
    <property name="statusCodes">
        <props>
            <prop key="errors/403">403</prop>
            <prop key="errors/404">404</prop>
        </props>
    </property>
</bean>

[/code]