这有点奇怪。我尝试通过操纵注释= RestController.class
来使用RestControllerAdvice捕获HttpRequestMethodNotSupportedException.class的异常但是,它不起作用。但是,当我删除注释时,它工作正常。我也尝试过basePackages,它是相同的-就像其他属性过滤器一样。
示例代码如下:
@RestControllerAdvice(annotations = RestController.class)
public class WebApiAdvice {
@ExceptionHandler(value = HttpRequestMethodNotSupportedException.class)
@ResponseStatus(HttpStatus.METHOD_NOT_ALLOWED)
protected Object methodNotSupportedErrorHandler(HttpServletRequest request, Exception exception) throws Exception {
return processAndResponse(request, exception, HttpStatus.METHOD_NOT_ALLOWED);
}
public ResponseEntity<ExceptionBean> processAndResponse(HttpServletRequest request, Exception exception, HttpStatus status) {
ExceptionBean exceptionBean = new ExceptionBean();
exceptionBean.setExceptionCode(status.name());
exceptionBean.setExceptionMessage("Message - "+status.getReasonPhrase());
System.out.println(exception.toString()+" "+exception.getMessage());
return new ResponseEntity(exceptionBean, status);
}
}
还有控制器:
@RestController
public class QueryResultController {
@RequestMapping(value="/websapi/queryResult", method = RequestMethod.POST)
public String viewResponse(@RequestBody String jSONData, HttpServletRequest request, HttpServletResponse response) {
System.out.println(request.getParameter("test"));
return "test";
}}
我的最终目标是为每种类型的ControllerAdvice和RestControllerAdvice提供一个Advice类。添加任何导致不起作用的属性过滤器(basePackages,注释等)。但是通过删除属性过滤器,它可以正常工作。它甚至可以按预期吐出JSON响应(用于RestControllerAdvice)。
日志很干净,因为它表明ControllerAdvice始终在两种情况下都已注册:
[localhost-startStop-5] o.s.w.s.m.m.a.ExceptionHandlerExceptionResolver - Detected @ExceptionHandler methods in webApiAdvice
这是dispatcher-servlet.xml中的设置:
<context:component-scan base-package="com.celtro.ken.op.support.util, com.celtro.ken.op.support.config, com.celtro.ken.op.support.advice, com.celtro.ken.op.support.interceptor, com.celtro.ken.op.controller" />
<mvc:annotation-driven />
我正在使用Spring 4.3.10。
在成功的情况下,它将在浏览器中吐出JSON即可:
{"exceptionCode":"METHOD_NOT_ALLOWED","exceptionMessage":"Message - Method Not Allowed"}
在失败的情况下,浏览器将吐出一个常见的Apache Tomcat错误:
HTTP Status 405 – Method Not Allowed
Type Status Report
Message Request method 'GET' not supported
Description The method received in the request-line is known by the origin server but not supported by the target resource.
Apache Tomcat/8.5.23
我已经尝试了一段时间。赞赏任何人以突出出现错误的地方。