为rest api返回一个漂亮的错误json

问题描述 投票:0回答:3

当我的基于 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
3个回答
0
投票

您正在寻找的是 @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的新创建的对象并返回它。

在您的控制器中,您需要抛出特定的异常。

还要注意,您需要创建 MyCustomException 来扩展异常。


0
投票

使用您自己的异常处理程序:

try {
   ...you code that throws AuthenticationServiceException
} catch (AuthenticationServiceException ex) {
   ... return you custom JSONObject
}

0
投票

在底层捕获所有异常,并转换为 JSON,然后返回异常的 JSON 表示形式,返回码为 400。

我最初包含示例代码来展示如何以标准化方式将异常转换为 JSON,包括指向开源库的链接以提供帮助,但这被认为是自我提升,因此被删除。

该形式推荐的JSON结构:

{
"error": {
  "code": "400",
  "message": "main error message here",
  "target": "approx what the error came from",
  "details": [
     {
        "code": "23-098a",
        "message": "Disk drive has frozen up again.  It needs to be replaced",
        "target": "not sure what the target is"
     }
  ],
  "innererror": {
     "trace": [ ... ],
     "context": [ ... ]
  }
}
}

这是 OASIS 数据标准 OASIS OData 提出的格式,似乎是最标准的选项,但目前任何标准的采用率似乎都不高。对此进行完整讨论的链接已被删除,因为它被认为是自我推销。

© www.soinside.com 2019 - 2024. All rights reserved.