@ControllerAdvice (REST 404) - erroneous exceptions

I am using Spring MVC 3.2.9 and am currently working on global error handling for the application. My error handling class is as follows:

@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);
    }
}

One of my controllers looks like this (simplified)

@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
    }
}

I am trying to raise a 404 error by throwing a NoSuchRequestHandlingMethodException, hoping my error handling class will catch it and return a ResponseEntity as indicated. But this is what happens instead:

If I make a request from a client as follows:

/modules/admin/form/addfsdfadf/

it should raise the specified exception since this mapping does not exist, right? But instead, an HttpRequestMethodNotSupportedException is thrown and handleHttpRequestMethodNotSupported is thrown.

Another example:

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

, , Tomcat 404 ( html).

, , - , , .

- , ? ? ?

, , handle 404, Tomcat . REST, 404 , JSON... ?

+4

Source: https://habr.com/ru/post/1548040/


All Articles