Bob*_*obo 6 exception-handling spring-mvc
代码是这样的:
@Controller
public class TestController {
@RequestMapping(value = "/testerror", method = RequestMethod.GET)
public @ResponseBody ErrorTO testerror(HttpServletRequest request,HttpServletResponse response) {
throw new ABCException("serious error!");
}
@ExceptionHandler(ABCException.class)
public @ResponseBody ErrorTO handleException(ABCException ex,
HttpServletRequest request, HttpServletResponse response) {
response.setStatus(response.SC_BAD_REQUEST);
return new ErrorTO(ex.getMessage());
}
@RequestMapping(value = "/test", method = RequestMethod.GET)
public @ResponseBody ErrorTO test(HttpServletRequest request,
HttpServletResponse response) {
ErrorTO error = new ErrorTO();
error.setCode(-12345);
error.setMessage("this is a test error.");
return error;
}
}
Run Code Online (Sandbox Code Playgroud)
当我尝试卷曲-H"接受:application/json"-v"http://localhost.com:8080/testerror"我收到此错误:org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerExceptionResolver - 找不到HttpMessageConverter,支持返回类型[类com.kibboko.poprocks.appservices.dtos.ErrorTO]和[application/json]
但如果我尝试卷曲-H"接受:application/json"-v"http://localhost.com:8080/test",工作并返回json响应."application/xml"也有效.
我需要处理的异常处理程序有什么特别之处,以便它可以与json或xml一起使用吗?谢谢!
它似乎AnnotationMethodHandlerExceptionResolver有自己的HttpMessageConverters 数组.您需要将其配置为使用相同的数组AnnotationMethodHandlerAdapter.
但是,AnnotationMethodHandlerAdapter隐式声明时可能会很复杂.FactoryBean在所有情况下,或许声明以下内容可能会有所帮助:
public class AnnotationMethodHandlerExceptionResolverFactoryBean
implements FactoryBean<AnnotationMethodHandlerExceptionResolver> {
@Autowired
private AnnotationMethodHandlerAdapter a;
public AnnotationMethodHandlerExceptionResolver getObject()
throws Exception {
AnnotationMethodHandlerExceptionResolver r = new AnnotationMethodHandlerExceptionResolver();
r.setMessageConverters(a.getMessageConverters());
return r;
}
...
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9553 次 |
| 最近记录: |