基于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。但这似乎不起作用。
任何指针为什么?
最佳答案
您正在寻找的是@ControllerAdvice。逻辑如下:
您可以创建一个带有注释的类,其中该类中的每个方法都会响应一个或多个异常。这里的例子:
@ControllerAdvice
public class MyExceptionHandler {
private static final Logger logger = LoggerFactory.getLogger(MyExceptionHandler.class);
@ExceptionHandler(MyCustomException.class)
@ResponseBody
public ExcObject handleSQLException(HttpServletRequest request, Exception ex){
logger.info("SQLException Occured:: URL="+request.getRequestURL());
return "database_error";
}
@ResponseStatus(value=HttpStatus.NOT_FOUND, reason="IOException occured")
@ExceptionHandler(IOException.class)
public void handleIOException(){
logger.error("IOException handler executed");
//returning 404 error code
}
}
在handleSQLException内部构造新创建的类ExcObject的新创建的对象,并返回该对象。
在您的 Controller 中,您需要引发特定的异常。
还请注意,您需要创建MyCustomException,它将扩展异常。
关于java - 返回REST API的漂亮错误JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31746251/