2

我正在为 Spring Boot 中的异常处理开发示例演示应用程序。我正在尝试使用 @ControllerAdvice 进行异常处理。

我想处理验证器抛出的异常。它处理其他异常,但不处理 MethodArgumentNotValidException。

有关更多详细信息,以下是我正在学习的课程:

查询.java

@Getter
@Setter
@NoArgsConstructor
@Validated
public class Query implements Serializable{
    @Size(min = 7, max = 24, message = "Size must be between 7 and 24")
    @Pattern(regexp = "[a-zA-Z0-9 ]+", Invalid characters")
    private String number;

    @Size(max = 2, message = "Size must be between 0 and 2")
    @Pattern(regexp = "[a-zA-Z0-9 ]+", message="Invalid characters")
    private String language;
}

错误响应.java

@Setter
@Getter
@NoArgsConstructor
@JsonInclude(JsonInclude.Include.NON_NULL)
@Data
public class ErrorResponse 
{

    @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd hh:mm:ss")
    private LocalDateTime timestamp;

    private HttpStatus status;

    private int code;

    private String error;

    private String exception;

    private String message;

    private String path;

    private List<String> errors;

}

CustomExceptionHandler.java

@SuppressWarnings({"unchecked","rawtypes"})
@ControllerAdvice
@Component("error")
public class CustomExceptionHandler extends ResponseEntityExceptionHandler {

    @ResponseStatus(HttpStatus.NOT_FOUND)
    @ExceptionHandler(NotFoundException.class)
    public final ResponseEntity<Object> handleNotFoundError(NotFoundException ex, final HttpServletRequest request) {
        ErrorResponse error = new ErrorResponse();
        error.setTimestamp(LocalDateTime.now());
        error.setMessage(ex.getMessage());
        error.setCode(HttpStatus.NOT_FOUND.value());
        return new ResponseEntity(error, HttpStatus.NOT_FOUND);
    }

    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(InternalServerException.class)
    public final ResponseEntity<Object> handleInternelServorError(InternalServerException ex, final HttpServletRequest request) {
        ErrorResponse error = new ErrorResponse();
        error.setTimestamp(LocalDateTime.now());
        error.setMessage(ex.getMessage());
        error.setCode(HttpStatus.INTERNAL_SERVER_ERROR.value());
        return new ResponseEntity(error, HttpStatus.INTERNAL_SERVER_ERROR);
    }

    @ExceptionHandler(ConstraintViolationException.class)
    public void constraintViolationException(HttpServletResponse response) throws IOException {
        response.sendError(HttpStatus.BAD_REQUEST.value());
    }

    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @Override
    protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
        List<String> errorList = ex
                .getBindingResult()
                .getFieldErrors()
                .stream()
                .map(fieldError -> fieldError.getDefaultMessage())
                .collect(Collectors.toList());
        ErrorResponse error = new ErrorResponse();
        error.setCode(HttpStatus.BAD_REQUEST.value());
        return new ResponseEntity(error, HttpStatus.BAD_REQUEST);
    }
}

要求

public ResponseEntity<?> getData(HttpServletRequest httpServletRequest,
            @Valid @ApiParam(value = "MANDATORY. The number") @PathVariable(value = "number", required = true) final String partNumber,
            @Valid @ApiParam(value = "OPTIONAL. The language") @RequestParam(value = "language", required = false) final String languageKey) {
.............
}
4

2 回答 2

0

您创建List<String> errorList但从不使用它并返回空ErrorResponse

于 2020-09-17T15:05:26.667 回答
0

我刚刚遇到了这个问题,这是我解决它的方法:

@ControllerAdvice
public class ApplicationExceptionHandler extends ResponseEntityExceptionHandler {   
    @Override
    protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
        // handle validation exception here
    }
}

注意:如果您有多个扩展类ResponseEntityExceptionHandler和全部类,@ControllerAdvice则执行此覆盖函数可能会遇到一些麻烦。为了最终使用它,我必须在所有异常处理程序的基类中覆盖它。将来,我可能会将所有异常处理程序放在一个类中以避免这种情况。

来源: https ://www.youtube.com/watch?v=Q0hwXOeMdUM

于 2021-11-29T16:56:49.100 回答