spring引导异常处理程序从未被调用

kpbwa7wx  于 2021-07-13  发布在  Java
关注(0)|答案(1)|浏览(296)

我使用的是SpringBootV2.2.10和SpringV5.2.9。我创建了一个带有 @Valid @RequestBody 注解。验证工作正常(我得到一个 400 BAD REQUEST 在提交超出约束的值时响应),但我不喜欢默认的错误消息,因为它显示了太多的内部信息。因此,我定义了 @ExceptionHandler(MethodArgumentNotValidException.class) 方法,但从未调用此方法。
这是具有异常处理程序的控制器:

import java.util.List;
import java.util.stream.Collectors;

import javax.validation.Valid;

import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import lombok.RequiredArgsConstructor;

@RestController
@RequiredArgsConstructor
@RequestMapping("/api/data")
public class DataController {

    @PostMapping(path = "/{id}", consumes = MediaType.APPLICATION_JSON_VALUE)
    private void postData(
            @PathVariable String id,
            @Valid @RequestBody MyDTO dto) {

        // DO SOMETHING

    }

    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public List<String> handleValidationExceptions(MethodArgumentNotValidException ex) {
        System.out.println("Handling method argument not valid exception");
        return ex.getBindingResult()
            .getAllErrors().stream()
            .map(ObjectError::getDefaultMessage)
            .collect(Collectors.toList());
    } 
}

dto:

import javax.validation.constraints.Max;
import lombok.Getter;

@Getter
public class MyDTO {

    @Max(value = 1, message = "Value should not be greater than 1")
    private float value;

}

我也试着把 ExceptionHandler 加入一个额外的班级:

// Imports

@Order(Ordered.HIGHEST_PRECEDENCE)
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(MethodArgumentNotValidException.class)
    // Same as before

}

如我所说,我的 ExceptionHandler 从不被调用。我可能做错了什么?

kzipqqlq

kzipqqlq1#

尝试从类responseentityexceptionhandler扩展并重写handlemethodargumentnotvalid

@Order(Ordered.HIGHEST_PRECEDENCE)
@ControllerAdvice
@Slf4j
public class ExceptionController extends ResponseEntityExceptionHandler {

@Override
protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex,
        HttpHeaders headers, HttpStatus status, WebRequest request) {
    return ...;
}

相关问题