处理 Jackson 在 Spring 端点上抛出的多个异常

Handling multiple exceptions thrown by Jackson on Spring endpoint

在下面的代码中,我公开了一个 POST 端点。 POST 的 return 值由 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 字符串存在问题一样(其中一个异常子句匹配)然后我无法 return 客户端的问题是什么,因为我无法将异常包装在 Json 对象中。所以我只是 return return {"exception": "true"};

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

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

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

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

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

您可以在 spring 控制器中处理具有 @ExceptionHandler 和 return 状态的异常作为 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);
}