首页 > 解决方案 > Spring ExceptionHandler for Request method 'POST' not supported

问题描述

I want to customize the response when a caller uses wrong HTTP method.

@RequestMapping(value = "/simulator/table/{id}/action", method = RequestMethod.PUT)
public GenericResponse doSomething(HttpServletRequest servletRequest, @PathVariable("id") String id, @RequestBody MyRequest request)
        throws BadRequestException, AuthorizationFailedException {
    return response;
}

I am able to catch many error states like malformed JSON input

@ExceptionHandler({HttpMessageNotReadableException.class})
public ResponseEntity resolveException(HttpServletRequest request, HttpMessageNotReadableException e) {
    log.error("Error when parsing the request {}\n{}", request.getRequestURI(), "a", e);
    GenericResponse response = new GenericResponse("FAILED", error);
    return new ResponseEntity<Object>(response, new HttpHeaders(), HttpStatus.BAD_REQUEST);
}

Now I want to catch when a client uses POST instead of PUT

This generic catcher does not work:

@ExceptionHandler
public ResponseEntity resolveException(HttpServletRequest request, Exception e) {
    log.error("Error when parsing the request {}\n{}", request.getRequestURI(), "a", e);
    GenericResponse response = new GenericResponse("FAILED", error);
    return new ResponseEntity<Object>(response, new HttpHeaders(), HttpStatus.BAD_REQUEST);
}

How can I catch and override it?

标签: javaspring-boot

解决方案


推荐阅读