@ControllerAdvice(REST 404) - 抛出错误的异常

时间:2014-07-11 08:52:57

标签: java spring spring-mvc tomcat spring-boot

我正在使用Spring MVC 3.2.9,我目前正致力于应用程序的全局错误处理。我的错误处理类看起来像这样:

@ControllerAdvice
public class ErrorController extends ResponseEntityExceptionHandler {

    @Override
    protected ResponseEntity<Object> handleNoSuchRequestHandlingMethod(NoSuchRequestHandlingMethodException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {

        //Some code

        return new ResponseEntity(ex, headers, status);
    }

    @Override
    protected ResponseEntity<Object> handleHttpRequestMethodNotSupported(HttpRequestMethodNotSupportedException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {

        //Some code

        return new ResponseEntity(ex, headers, status);
    }
}

我的一个控制器看起来像这样(简化)

@Controller
public class FormController {

    @ResponseBody
    @RequestMapping(value = "/modules/admin/form/add/", method = RequestMethod.POST)
    public void createForm(@RequestBody Form form) {
        //add form
    }

    @ResponseBody
    @RequestMapping(value = "/modules/admin/form/{formId}/details/field/add/", method = RequestMethod.POST)
    public void createField(@PathVariable Long formId, @RequestBody Field field) {
        //add field
    }
}

我试图通过触发NoSuchRequestHandlingMethodException来提出404错误,希望我的错误处理类能够捕获它并按照规定返回ResponseEntity。但这就是发生的事情:

如果我向客户提出这样的请求:

/modules/admin/form/addfsdfadf/

它应该触发所述异常,因为这个映射不存在,对吧?但是抛出HttpRequestMethodNotSupportedException并调用handleHttpRequestMethodNotSupported。

另一个例子:

/modules/admin/form/1232313423/details/field/addhfddfhfghsdfhs/

这个映射也不存在,但它完全绕过了我的错误处理机制,我在响应中获得了简单的旧Tomcat 404页面(纯HTML)。

我已经对此进行了测试,似乎请求中的字符数量以某种方式确定了我将获得哪种响应,在我的情况下,它们都是错误的。

谁能弄明白这里发生了什么?这是一个错误还是预期的行为?我做错了吗?

我真正想要的是处理404而不获取默认的Tomcat页面或我自己的默认页面。这是REST控制器,如果404发生,我想获得JSON响应......这可能吗?

0 个答案:

没有答案
相关问题