全书目录

第四篇:Spring Boot 完全指南 —— 政务大厅宇宙

第十二章:校验和统一异常处理 —— 材料不齐就别让窗口自由发挥

1 分钟 27 字 第 103 / 962 个阅读单元

校验先做,错误统一返回,不要每个窗口自己发明错误格式。

java
package com.example.cityhall.shared;

import org.springframework.http.HttpStatus;
import org.springframework.http.ProblemDetail;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.*;

@RestControllerAdvice
public class ApiExceptionHandler {

  @ExceptionHandler(MethodArgumentNotValidException.class)
  @ResponseStatus(HttpStatus.BAD_REQUEST)
  public ProblemDetail handleValidation(MethodArgumentNotValidException ex) {
    ProblemDetail detail = ProblemDetail.forStatus(HttpStatus.BAD_REQUEST);
    detail.setTitle("Invalid Request");
    detail.setDetail("request body validation failed");
    return detail;
  }
}