使Spring的@RequestBody注释在失败时返回自定义响应

时间:2018-08-07 08:32:10

标签: spring spring-boot

我有一个控制器,如下所示:

public void createEntity(@Valid @RequestBody final MyEntity myEntity) {}

但是,当对象转换失败时,API会自动返回带有Java堆栈跟踪的400。如何修改此故障响应? (我希望更改或删除回复消息。)

2 个答案:

答案 0 :(得分:1)

下面是一个使用@ExceptionHandler注释的示例

@RestController
public class Controller {

    @RequestMapping(value = "/", method = RequestMethod.POST)
    public void createEntity(@Valid @RequestBody final MyEntity myEntity) {
        //
    }


    @ControllerAdvice
    public class RestEndpointExceptionHandler { 

        @ExceptionHandler(MethodArgumentNotValidException.class)
        public ResponseEntity<Object> handleNotValidExceptionException(HttpServletRequest req, MethodArgumentNotValidException ex) {
          Object customException = "Validation failed";
          return new ResponseEntity<Object>(customException, HttpStatus.BAD_REQUEST);
        }

    }
}

我在here中推送了代码

答案 1 :(得分:1)

您可以将@ExceptionHandler@ResponseStatus一起使用,并将处理程序保留为空,以便仅返回状态码。

@ExceptionHandler(EmptyResultDataAccessException.class)
@ResponseStatus(HttpStatus.NOT_FOUND)
public void notFoundException() {
}