我这样做:
/**
* Global exception handler for unhandled errors.
* @author Varun Achar
* @since 2.0
* @version 1.0
*
*/
public class Http500ExceptionResolver extends SimpleMappingExceptionResolver
{
@Inject
private ViewResolver resolver;
@Override
public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
{
ModelAndView mv = new ModelAndView();
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
if(CommonUtil.isAjax(request))
{
MappingJackson2JsonView view = new MappingJackson2JsonView();
view.setObjectMapper(JsonUtil.getObjectMapper());
mv.addObject("responseMessage", "We had some problems while serving your request. We are looking into it");
mv.addObject("responseCode", GenericResponse.ERROR.code());
mv.addObject("success", false);
mv.setView(view);
}
else
{
mv.setViewName(resolver.getView(ViewConstants.ERROR_PAGE));
}
return mv;
}
}
在我的 servlet-context 中:
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerExceptionResolver">
<property name="order" value="0" />
</bean>
<bean id="securityExceptionResolver"
class="com.trelta.commons.utils.security.SecurityExceptionResolver">
<property name="order" value="1"></property>
<property name="exceptionMappings">
<map>
<entry key="org.springframework.security.access.AccessDeniedException"
value="/common/accessDenied"></entry>
<entry key="org.springframework.security.core.AuthenticationException"
value="/common/authenticationFailure"></entry>
</map>
</property>
</bean>
<bean id="http500ExceptionResolver"
class="com.trelta.commons.utils.security.Http500ExceptionResolver">
<property name="order" value="3" />
</bean>
order 字段很重要,因为 Spring 按该顺序循环通过异常解析器。您还可以为自己定义此类异常映射,一切顺利!
检查此博客文章和 javadoc 以获取SimpleMappingExceptionResolver