<ruby id="bdb3f"></ruby>

    <p id="bdb3f"><cite id="bdb3f"></cite></p>

      <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
        <p id="bdb3f"><cite id="bdb3f"></cite></p>

          <pre id="bdb3f"></pre>
          <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

          <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
          <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

          <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                <ruby id="bdb3f"></ruby>

                ??碼云GVP開源項目 12k star Uniapp+ElementUI 功能強大 支持多語言、二開方便! 廣告
                # Spring Boot 異常處理 – `@ExceptionHandler`示例 > 原文: [https://howtodoinjava.com/spring-boot2/spring-rest-request-validation/](https://howtodoinjava.com/spring-boot2/spring-rest-request-validation/) 在本**SpringBoot 異常處理器**教程中,我們將學習**驗證發送到 PUT / POST REST API 的請求正文**。 我們還將學習在驗證錯誤的 API 響應中添加自定義錯誤消息。 在這個 SpringBoot 示例中,我們將主要看到兩個主要的驗證案例: 1. HTTP POST `/employees`和請求正文不包含有效值,或者某些字段丟失。 它將在響應正文中返回 HTTP 狀態代碼 400,并帶有正確的消息。 2. HTTP GET `/employees/{id}`和無效 ID 在請求中發送。 它將在響應正文中返回帶有正確消息的 HTTP 狀態代碼 404。 > 閱讀更多: [HTTP 狀態代碼](https://restfulapi.net/http-status-codes/) ## 1\. 創建 REST API 和模型類 給定的 REST API 來自員工管理模塊。 `EmployeeRESTController.java` ```java @PostMapping(value = "/employees") public ResponseEntity<EmployeeVO> addEmployee (@RequestBody EmployeeVO employee) { EmployeeDB.addEmployee(employee); return new ResponseEntity<EmployeeVO>(employee, HttpStatus.OK); } @GetMapping(value = "/employees/{id}") public ResponseEntity<EmployeeVO> getEmployeeById (@PathVariable("id") int id) { EmployeeVO employee = EmployeeDB.getEmployeeById(id); if(employee == null) { throw new RecordNotFoundException("Invalid employee id : " + id); } return new ResponseEntity<EmployeeVO>(employee, HttpStatus.OK); } ``` `EmployeeVO.java` ```java @XmlRootElement(name = "employee") @XmlAccessorType(XmlAccessType.FIELD) public class EmployeeVO extends ResourceSupport implements Serializable { private Integer employeeId; private String firstName; private String lastName; private String email; public EmployeeVO(Integer id, String firstName, String lastName, String email) { super(); this.employeeId = id; this.firstName = firstName; this.lastName = lastName; this.email = email; } public EmployeeVO() { } //Removed setter/getter for readability } ``` ## 2\. Spring Boot 異常處理 – REST 請求驗證 #### 2.1. 默認的 Spring 驗證支持 要應用默認驗證,我們只需要在適當的位置添加相關注解即可。 即 1. **使用所需的驗證特定注解(例如`@NotEmpty`,`@Email`等)注解模型類**。 ```java @XmlRootElement(name = "employee") @XmlAccessorType(XmlAccessType.FIELD) public class EmployeeVO extends ResourceSupport implements Serializable { private static final long serialVersionUID = 1L; public EmployeeVO(Integer id, String firstName, String lastName, String email) { super(); this.employeeId = id; this.firstName = firstName; this.lastName = lastName; this.email = email; } public EmployeeVO() { } private Integer employeeId; @NotEmpty(message = "first name must not be empty") private String firstName; @NotEmpty(message = "last name must not be empty") private String lastName; @NotEmpty(message = "email must not be empty") @Email(message = "email should be a valid email") private String email; //Removed setter/getter for readability } ``` 2. **通過`@Valid`注解啟用驗證請求正文** ```java @PostMapping(value = "/employees") public ResponseEntity<EmployeeVO> addEmployee (@Valid @RequestBody EmployeeVO employee) { EmployeeDB.addEmployee(employee); return new ResponseEntity<EmployeeVO>(employee, HttpStatus.OK); } ``` #### 2.2. 異常模型類 默認的 Spring 驗證有效并提供有關錯誤的信息過多,這就是為什么我們應根據應用程序的需要對其進行自定義。 我們將僅提供措辭非常明確的必要錯誤信息。 不建議提供其他信息。 創建有意義的異常并充分描述問題始終是一個很好的建議。 一種方法是創建單獨的類來表示特定的業務用例失敗,并在該用例失敗時返回它們。 > 閱讀更多: [Java 異常處理 – 新的應用程序](https://howtodoinjava.com/java/exception-handling/best-practices-for-for-exception-handling/) 例如我為所有通過 ID 要求資源但在系統中找不到資源的場景創建了`RecordNotFoundException`類。 `RecordNotFoundException.java` ```java package com.howtodoinjava.demo.exception; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ResponseStatus; @ResponseStatus(HttpStatus.NOT_FOUND) public class RecordNotFoundException extends RuntimeException { public RecordNotFoundException(String exception) { super(exception); } } ``` 同樣,我編寫了一個特殊的類,將為所有失敗情況返回該類。 所有 API 具有一致的錯誤消息結構,可幫助 API 使用者編寫更健壯的代碼。 `ErrorResponse.java` ```java import java.util.List; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement(name = "error") public class ErrorResponse { public ErrorResponse(String message, List<String> details) { super(); this.message = message; this.details = details; } //General error message about nature of error private String message; //Specific errors in API request processing private List<String> details; //Getter and setters } ``` #### 2.3. 自定義`ExceptionHandler` 現在添加一個擴展`ResponseEntityExceptionHandler`的類,并使用`@ControllerAdvice`注解對其進行注解。 `ResponseEntityExceptionHandler`是一個方便的基類,用于通過`@ExceptionHandler`方法跨所有`@RequestMapping`方法提供集中式異常處理。 `@ControllerAdvice`更多用于在應用程序啟動時啟用自動掃描和配置。 用于**`@ControllerAdvice`異常處理示例**的 Java 程序。 `CustomExceptionHandler.java` ```java package com.howtodoinjava.demo.exception; import java.util.ArrayList; import java.util.List; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.validation.ObjectError; import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.context.request.WebRequest; import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler; @SuppressWarnings({"unchecked","rawtypes"}) @ControllerAdvice public class CustomExceptionHandler extends ResponseEntityExceptionHandler { @ExceptionHandler(Exception.class) public final ResponseEntity<Object> handleAllExceptions(Exception ex, WebRequest request) { List<String> details = new ArrayList<>(); details.add(ex.getLocalizedMessage()); ErrorResponse error = new ErrorResponse("Server Error", details); return new ResponseEntity(error, HttpStatus.INTERNAL_SERVER_ERROR); } @ExceptionHandler(RecordNotFoundException.class) public final ResponseEntity<Object> handleUserNotFoundException(RecordNotFoundException ex, WebRequest request) { List<String> details = new ArrayList<>(); details.add(ex.getLocalizedMessage()); ErrorResponse error = new ErrorResponse("Record Not Found", details); return new ResponseEntity(error, HttpStatus.NOT_FOUND); } @Override protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex, HttpHeaders headers, HttpStatus status, WebRequest request) { List<String> details = new ArrayList<>(); for(ObjectError error : ex.getBindingResult().getAllErrors()) { details.add(error.getDefaultMessage()); } ErrorResponse error = new ErrorResponse("Validation Failed", details); return new ResponseEntity(error, HttpStatus.BAD_REQUEST); } } ``` 上面的類處理多個異常,包括`RecordNotFoundException`; 并且還可以處理`@RequestBody`帶注解的對象中的請求驗證錯誤。 讓我們看看它是如何工作的。 ## 3\. Spring Boot 異常處理 – 演示 1)HTTP GET `/employees/1` [有效] ```java HTTP Status : 200 { "employeeId": 1, "firstName": "John", "lastName": "Wick", "email": "howtodoinjava@gmail.com", } ``` 2)HTTP GET `/employees/23` [無效] ```java HTTP Status : 404 { "message": "Record Not Found", "details": [ "Invalid employee id : 23" ] } ``` 3)HTTP POST `/employees` [無效] `Request` ```java { "lastName": "Bill", "email": "ibill@gmail.com" } ``` `Response` ```java HTTP Status : 400 { "message": "Validation Failed", "details": [ "first name must not be empty" ] } ``` 4)HTTP POST `/employees` [無效] `Request` ```java { "email": "ibill@gmail.com" } ``` `Response` ```java HTTP Status : 400 { "message": "Validation Failed", "details": [ "last name must not be empty", "first name must not be empty" ] } ``` 5)HTTP POST `/employees` [無效] `Request` ```java { "firstName":"Lokesh", "email": "ibill_gmail.com" //invalid email in request } ``` `Response` ```java HTTP Status : 400 { "message": "Validation Failed", "details": [ "last name must not be empty", "email should be a valid email" ] } ``` ## 4\. REST 請求驗證注解 在上面的示例中,我們僅使用了很少的注解,例如`@NotEmpty`和`@Email`。 還有更多此類注解可用于驗證請求數據。 必要時將其簽出。 | 注解 | 用法 | | --- | --- | | `@AssertFalse` | 帶注解的元素必須為`false`。 | | `@AssertTrue` | 帶注解的元素必須為`true`。 | | `@DecimalMax` | 帶注解的元素必須是一個數字,其值必須小于或等于指定的最大值。 | | `@DecimalMin` | 帶注解的元素必須是一個數字,其值必須大于或等于指定的最小值。 | | `@Future` | 帶注解的元素必須是將來的瞬間,日期或時間。 | | `@Max` | 帶注解的元素必須是一個數字,其值必須小于或等于指定的最大值。 | | `@Min` | 帶注解的元素必須是一個數字,其值必須大于或等于指定的最小值。 | | `@Negative` | 帶注解的元素必須是嚴格的負數。 | | `@NotBlank` | 帶注解的元素不能為`null`,并且必須至少包含一個非空白字符。 | | `@NotEmpty` | 帶注解的元素不能為`null`,也不能為空。 | | `@NotNull` | 帶注解的元素不能為`null`。 | | `@Null` | 帶注解的元素必須為`null`。 | | `@Pattern` | 帶注解的`CharSequence`必須與指定的正則表達式匹配。 | | `@Positive` | 帶注解的元素必須是嚴格的正數。 | | `@Size` | 帶注解的元素大小必須在指定的邊界(包括在內)之間。 | ## 5\. 總結 在此**Spring REST 驗證教程**中,我們學習了: * 通過 ID 提取資源時驗證 ID。 * 驗證 POST / PUT API 中的請求正文字段。 * 在 API 響應中發送一致且結構化的錯誤響應。 將有關 **spring rest 異常處理**的問題交給我。 學習愉快! 參考:[`javax.validation.constraints`包](https://javaee.github.io/javaee-spec/javadocs/javax/validation/constraints/package-summary.html)
                  <ruby id="bdb3f"></ruby>

                  <p id="bdb3f"><cite id="bdb3f"></cite></p>

                    <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
                      <p id="bdb3f"><cite id="bdb3f"></cite></p>

                        <pre id="bdb3f"></pre>
                        <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

                        <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
                        <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

                        <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                              <ruby id="bdb3f"></ruby>

                              哎呀哎呀视频在线观看