【问题标题】:Handling multiple exceptions thrown by Jackson on Spring endpoint处理杰克逊在 Spring 端点上抛出的多个异常
【发布时间】:2015-05-18 14:09:10
【问题描述】:

在下面的代码中,我公开了一个 POST 端点。 POST 的返回值由 Success 对象上的布尔属性确定:

@RequestMapping(value="/new", method = RequestMethod.POST,produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public String createDispatch(@RequestParam(value="p1") String p1) {

    Success ds = new Success();
    //Set a boolean on Success object to true
    ObjectMapper mapper = new ObjectMapper();

    try {
        return mapper.writeValueAsString(ds);
    } catch (JsonGenerationException e) {
        e.printStackTrace();
        return {"exception": "true"};
    } catch (JsonMappingException e) {
        e.printStackTrace();
        return {"exception": "true"};
    } catch (IOException e) {
        e.printStackTrace();
        return {"exception": "true"};
    }

}

在写入转换为 JSON (return mapper.writeValueAsString(ds)) 时捕获每种异常类型似乎是多余的,好像创建 JSON 字符串时存在问题(匹配异常子句之一)然后我无法返回问题所在客户端,因为我无法将异常包装在 Json 对象中。所以我只返回 return {"exception": "true"};

我应该返回什么来封装应该抛出的异常类型?

【问题讨论】:

    标签: java spring post jackson endpoints


    【解决方案1】:

    您可以在 spring 控制器中使用@ExceptionHandler 处理异常,并将状态作为 HTTP 响应状态代码或任何对象,甚至作为序列化为 JSON 的异常返回。

    @RequestMapping(value="/new")
    @ResponseBody
    public String createDispatch(@RequestParam(value="p1") String p1) {
        Success ds = new Success();
        ObjectMapper mapper = new ObjectMapper();    
        return mapper.writeValueAsString(ds);
    }      
    
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ResponseBody
    public String handleAnyException(Exception exception) {
        return formatExceptionAsJson(exception);
    }
    

    【讨论】:

      【解决方案2】:

      如果您以相同的方式处理每个异常,并且只需要您可能使用的相关信息

          try {
              return mapper.writeValueAsString(ds);
          } catch (Exception e) {
              e.printStackTrace();
              return {"exception":"true", "exceptionClass":e.getClass().getName(),
                      "exceptionMessage":e.getMessage()};
          }
      

      这样,您将获得有关发生异常的一些相关信息。

      您可以返回任何您认为有用的 DTO 的 json。

      【讨论】:

        猜你喜欢
        • 2015-01-24
        • 2023-03-27
        • 2019-05-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-07-05
        • 2012-09-13
        • 1970-01-01
        相关资源
        最近更新 更多