私はそれをこのようにします:
/**
* 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;
}
}
そして私のサーブレットコンテキストでは:
<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>
Springは例外リゾルバーをこの順序で循環するため、順序フィールドは重要です。この種の例外マッピングを自分で定義することもできます。
SimpleMappingExceptionResolverについては、このブログ投稿とjavadocを確認してください