<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 REST 異常處理示例 > 原文: [https://howtodoinjava.com/spring-restful/exception-handling-example/](https://howtodoinjava.com/spring-restful/exception-handling-example/) 在使用 **Spring REST** 模塊創建的 [REST API](https://restfulapi.net) 中學習處理異常(請求驗證,錯誤數據或其他請求處理錯誤)。 我們將研究一種使用`@ControllerAdvice`和`@ExceptionHandler`的方法。 要使用`@ControllerAdvice`全局處理 REST 異常,我們需要遵循以下步驟。 ## 1\. 使用`@ControllerAdvice`和`@ExceptionHandler`創建處理器 * [`@ControllerAdvice`](https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/bind/annotation/ControllerAdvice.html)注解是`@Component`注解的特化,其方法(以[`@ExceptionHandler`](https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/bind/annotation/ExceptionHandler.html)注解)在全球范圍內跨多個`@Controller`類共享。 * 通過類路徑掃描自動檢測帶有`@ControllerAdvice`的類。 * 使用選擇器`annotations()`,`basePackageClasses()`和`basePackages()`定義目標控制器的更窄子集。 * 我們可以在選擇器中應用 OR 運算符,即如果遇到給定異常中的任何一個,則將執行給定方法。 請注意,[`ResponseEntityExceptionHandler`](https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/servlet/mvc/method/annotation/ResponseEntityExceptionHandler.html)是`@ControllerAdvice`類的便捷基類,這些類希望通過`@ExceptionHandler`方法跨所有`@RequestMapping`方法提供集中的[異常處理](https://howtodoinjava.com/best-practices/java-exception-handling-best-practices/) 。 `CustomExceptionHandler.java` ```java import java.util.ArrayList; import java.util.List; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; 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; @ControllerAdvice public class CustomExceptionHandler extends ResponseEntityExceptionHandler { private String INCORRECT_REQUEST = "INCORRECT_REQUEST"; private String BAD_REQUEST = "BAD_REQUEST"; @ExceptionHandler(RecordNotFoundException.class) public final ResponseEntity<ErrorResponse> handleUserNotFoundException (RecordNotFoundException ex, WebRequest request) { List<String> details = new ArrayList<>(); details.add(ex.getLocalizedMessage()); ErrorResponse error = new ErrorResponse(INCORRECT_REQUEST, details); return new ResponseEntity<>(error, HttpStatus.NOT_FOUND); } @ExceptionHandler(MissingHeaderInfoException.class) public final ResponseEntity<ErrorResponse> handleInvalidTraceIdException (MissingHeaderInfoException ex, WebRequest request) { List<String> details = new ArrayList<>(); details.add(ex.getLocalizedMessage()); ErrorResponse error = new ErrorResponse(BAD_REQUEST, details); return new ResponseEntity<>(error, HttpStatus.BAD_REQUEST); } } ``` ## 2\. 創建異常模型類 我們需要識別業務異常用例,并用異常類來表示它們。 這些類將擴展`RuntimeException`類。 也可以根據需要隨意創建更多錯誤響應表示。 `MissingHeaderInfoException.java` ```java import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ResponseStatus; @ResponseStatus(HttpStatus.BAD_REQUEST) public class MissingHeaderInfoException extends RuntimeException { private static final long serialVersionUID = 1L; public MissingHeaderInfoException(String message) { super(message); } } ``` `RecordNotFoundException.java` ```java import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ResponseStatus; @ResponseStatus(HttpStatus.NOT_FOUND) public class RecordNotFoundException extends RuntimeException { private static final long serialVersionUID = 1L; public RecordNotFoundException(String message) { super(message); } } ``` `ErrorResponse.java` ```java import java.util.List; public class ErrorResponse { public ErrorResponse(String message, List<String> details) { super(); this.message = message; this.details = details; } private String message; private List<String> details; //getters and setters } ``` ## 3\. 配置視圖解析器 如果尚未完成,我們需要配置視圖解析器以將異常消息轉換為 XML 或 JSON 形式。 在 Spring Boot 中,此配置是自動完成的。 沒有 SpringBoot,我們需要像下面這樣。 > 重要說明:確保已啟用`mvc: annotation-driven`配置,或已使用`@EnableWebMvc`注解。 `rest-servlet.xml` ```java <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:jpa="http://www.springframework.org/schema/data/jpa" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <mvc:annotation-driven /> <context:component-scan base-package="com.howtodoinjava.demo" /> <mvc:view-resolvers> <mvc:content-negotiation> <mvc:default-views> <bean class="org.springframework.web.servlet.view.json.MappingJackson2JsonView"/> </mvc:default-views> </mvc:content-negotiation> </mvc:view-resolvers> <!-- JPA Config --> </beans> ``` ## 4\. REST 控制器更改 從 rest 控制器處理器方法中,我們需要拋出要轉換并作為響應發送給 API 使用者的異常。 在這種情況下,如果`id`搜索了一個雇員并且該雇員在數據庫中不存在,我們將發送`RecordNotFoundException`。 `EmployeeRESTController.java` ```java @GetMapping("/employees/{id}") Employee getEmployeeById(@PathVariable Long id) { return repository.findById(id) .orElseThrow(() -> new RecordNotFoundException("Employee id '" + id + "' does no exist")); } ``` ## 5\. Spring REST 異常處理演示 嘗試按 ID(在數據庫中不存在 ID)獲取員工。 `API Request` ```java HTTP GET : http://localhost:8080/SpringRestExample/api/rest/employee-management/employees/101 ``` `API Response` ```java { "message": "INCORRECT_REQUEST", "details": [ "Employee id '101' does no exist" ], } ``` 請把關于 Spring Rest API 中的**異常處理**的問題交給我。 學習愉快! [下載源碼](https://howtodoinjava.com/wp-content/downloads/SpringRestExample.zip)
                  <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>

                              哎呀哎呀视频在线观看