我想创建一个异常处理程序,它将拦截我项目中的所有控制器.这可能吗?看起来我必须在每个控制器中放置一个处理程序方法.谢谢你的帮助.我有一个发送Json响应的弹簧控制器.因此,如果发生异常,我想发送一个可以从一个地方控制的错误响应.
首先,我想评论一下,我已经检查了Stack Overflow中的其他问题,并根据答案实现了我自己的方法:https://stackoverflow.com/a/14425801/2487263和/sf/answers/1127115461/
我试图在Spring 3.2,Spring MVC应用程序中使用Spring安全3.1来保护REST API,我使用简单配置的基本身份验证方法:
<http create-session="stateless" entry-point-ref="authenticationFailedEntryPoint">
<intercept-url pattern="/**" access="ROLE_USER"/>
<http-basic />
</http>
Run Code Online (Sandbox Code Playgroud)
如您所见,我使用自定义入口点,我有自己的ErrorResponse对象,我将以json格式添加到http响应,请参阅下面的代码:
@Component
public class AuthenticationFailedEntryPoint implements AuthenticationEntryPoint {
static Logger log = Logger.getLogger(AuthenticationFailedEntryPoint.class);
@Override
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
log.error(ExceptionUtils.getStackTrace(authException));
ErrorResponse errorResponse = new ErrorResponse();
... here I fill my errorResponse object ...
ObjectMapper jsonMapper = new ObjectMapper();
response.setContentType("application/json;charset=UTF-8");
response.setStatus(status);
PrintWriter out = response.getWriter();
out.print(jsonMapper.writeValueAsString(errorResponse));
}
}
Run Code Online (Sandbox Code Playgroud)
我尝试了两种测试用例的方法:
这是请求/响应:
GET http://localhost:8081/accounts/accounts?accountNumber=1013
-- …Run Code Online (Sandbox Code Playgroud)