Spring @ExceptionHandler does not work with @ResponseBody

后端 未结 7 1605
南笙
南笙 2020-11-29 23:45

I try to configure a spring exception handler for a rest controller that is able to render a map to both xml and json based on the incoming accept header. It throws a 500 se

7条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-30 00:35

    I faced the similar issue, this problem occurs when your Controller method return type and ExceptionHandler return types are not same. Make sure you have exactly same return types.

    Controller method:

    @RequestMapping(value = "/{id}", produces = "application/json", method = RequestMethod.POST)
    public ResponseEntity getUserById(@PathVariable String id) throws NotFoundException {
        String response = userService.getUser(id);
        return new ResponseEntity(response, HttpStatus.OK);
    }
    

    Advice method:

    @ExceptionHandler(NotFoundException.class)
    public ResponseEntity notFoundException(HttpServletRequest request, NotFoundException e) {
        ExceptionResponse response = new ExceptionResponse();
        response.setSuccess(false);
        response.setMessage(e.getMessage());
        return new ResponseEntity(response, HttpStatus.NOT_FOUND);
    }
    

    As you can see return types in both the classes are same ResponseEntity.

提交回复
热议问题