【发布时间】:2015-10-23 03:18:08
【问题描述】:
当我的基于 Java 的 REST Web 服务发生错误时 我像这样将异常发送给客户端
type Exception report
message Invalid Token
description The server encountered an internal error that prevented it from fulfilling this request.
exception
org.springframework.security.authentication.AuthenticationServiceException: Invalid Token
com.resource.security.TokenAuthenticationFilter.doFilter(TokenAuthenticationFilter.java:220)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:110)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:50)
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:108)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:87)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:192)
org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:160)
org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:344)
org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:261)
com.thetransactioncompany.cors.CORSFilter.doFilter(CORSFilter.java:208)
com.thetransactioncompany.cors.CORSFilter.doFilter(CORSFilter.java:271)
note The full stack trace of the root cause is available in the Apache Tomcat/8.0.23 logs.
但我想返回这样的响应
{
"code" : 500,
"message" : "invalid token"
}
如何做到这一点?
更新
@Provider
public class MyApplicationExceptionHandler implements
ExceptionMapper<WebApplicationException> {
@Override
public Response toResponse(WebApplicationException weException) {
// get initial response
Response response = weException.getResponse();
// create custom error
ErrorDTO error = new ErrorDTO();
error.setCode(response.getStatus());
error.setMessage(weException.getMessage());
// return the custom error
return Response.status(response.getStatus()).entity(error).build();
}
}
Web.xml
<context-param>
<param-name>resteasy.providers</param-name>
<param-value>com.madzz.common.exception.MadzzApplicationExceptionHandler</param-value>
</context-param>
应用代码:
public String getTrackingDetailById(long orderItemId) throws Exception {
throw new NotFoundException("not found"); }
我正在使用 java.ws.rs.NotFoundException 。但这似乎不起作用。 任何指针为什么?
【问题讨论】:
-
只捕获异常并返回您自己的代码...
标签: java json rest exception error-handling