java - 返回REST API的漂亮错误JSON

标签 java json rest exception error-handling

基于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/

相关文章:

rest - 如何使用证书 golang 发送 https 请求

mysql - 如何使用 Talend RestFul Services 将数据发布到多个表中

java - 有循环的树

java - 每个句子前面加两个空格

c# - 反序列化使得字段是一个空列表而不是 null

javascript - 从文本文件加载 json 数据时出现空白页

java - hashcode() 是从信息列表中计算唯一标记的好方法吗?

java - 我们如何自定义 Mahout 的 FileDataModel delimiterPattern?

javascript - ajax调用成功的for循环不起作用

java - RESTful 应用程序的 @ResponseStatus Spring 批注究竟如何工作?