我正在处理一些负面的情况,比如调用GET API,这实际上是一个POST调用。这给出了Spring状态为405的方法未找到错误。
但我想要自己的异常,所以我添加了以下解析器:
public class HandlerExceptionResolver
implements org.springframework.web.servlet.HandlerExceptionResolver {
protected final Log logger = LogFactory.getLog(this.getClass());
@Override
public ModelAndView resolveException(
HttpServletRequest request, HttpServletResponse response,
Object handler,Exception exception) {
logger.trace("-------------doResolveException-------------");
System.out.println("-------------doResolveException-------------");
if(exception instanceof HttpRequestMethodNotSupportedException) {
Fault fault = new Fault();
ObjectMapper mapper = new ObjectMapper();
mapper.setSerializationInclusion(Include.NON_NULL);
String errorMessage;
try {
errorMessage = mapper.writeValueAsString(fault);
response.setStatus(405);
response.setContentType("application/json");
response.getWriter().println(errorMessage);
response.getWriter().flush();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return null;
}但这并不会将JSON写入响应。
发布于 2018-05-11 01:38:13
我认为您不应该想要使用该response参数编写自己的输出。Spring期望您的方法返回一个ModelAndView实例,您可以用想要发送给用户的数据(模型部分)和将用于呈现它的视图资源的名称填充该实例。然后,您还需要定义一个新的视图资源,该资源将从ModelAndView中的数据中生成所需的JSON……
发布于 2018-05-11 01:45:58
至于关注点,你能调试出
errorMessage = mapper.writeValueAsString(fault);
有更好的方法来处理这种异常。
@ExceptionHandler(HandlerExceptionResolver.class)
public ModelAndView handleEmployeeNotFoundException(HttpServletRequest request, Exception ex){
logger.error("Requested URL="+request.getRequestURL());
logger.error("Exception Raised="+ex);
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("exception", ex);
modelAndView.addObject("url", request.getRequestURL());
modelAndView.setViewName("error");
return modelAndView;
} 如果您想使用@ExceptionHandler来处理这种情况,也可以尝试一下。
https://stackoverflow.com/questions/50278225
复制相似问题