sprig中基於註解的異常處理
本文簡述在spring中使用註解對Controller中丟擲的異常進行單獨處理或統一處理。
1、單獨處理當前controller中的異常
主要的controller程式碼如下,程式碼中訪問hello時會直接丟擲DuplicateElementException異常從而執行exception中的返回。使用瀏覽器可以看到返回"Hello,world"的字樣。
package cn.hifei.spring.demo.web.controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.mchange.util.DuplicateElementException;
@RestController
public class TestController {
@ExceptionHandler(DuplicateElementException.class)
public String exeption() {
return "Hello,world";
}
@RequestMapping(value="hello",method=RequestMethod.GET)
public String test() throws Exception {
throw new DuplicateElementException();
}
}
2、統一處理異常
當需要對多個controller中丟擲的異常進行統一處理時,可以使用@RestControllerAdvice或@ControllerAdvice標註一個異常處理類,由於@RestControllerAdvice(在基於spring的restful的controller中使用)或@ControllerAdvice(在普通的controller中使用)中已經使用了@Component註解,因此可以自動被掃描到。如下
package cn.hifei.spring.demo.web.exception;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@RestControllerAdvice
public class AppWideExceptionHandler {
@ExceptionHandler(IllegalArgumentException.class)
public String exceptionHandler() {
return "Oh,No!";
}
}
測試的controller程式碼如下:
當訪問hello2時會直接丟擲IllegalArgumentException異常從而跳轉到AppWideExceptionHandler類中的exceptionHandler方法中執行,瀏覽器上可以看到"Oh,No!"的字樣。
package cn.hifei.spring.demo.web.controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.mchange.util.DuplicateElementException;
@RestController
public class TestController {
@ExceptionHandler(DuplicateElementException.class)
public String exeption() {
return "Hello,world";
}
@RequestMapping(value="hello2",method=RequestMethod.GET)
public String test2() throws IllegalArgumentException{
throw new IllegalArgumentException();
}
}
相關文章
- 基於Gin框架實現異常處理框架
- SpringBoot中異常處理Spring Boot
- Python基礎 -- 異常處理Python
- Ruby中的TypeError異常處理Error
- 異常的處理
- 異常-throws的方式處理異常
- 異常篇——異常處理
- Spring Boot 中關於自定義異常處理的套路!Spring Boot
- PHP基礎:異常處理ExceptionPHPException
- python 基礎之異常處理Python
- C#基礎之前處理器,異常處理C#
- spring中的統一異常處理Spring
- springboot專案中的異常處理Spring Boot
- SpringBoot中的全域性異常處理Spring Boot
- python異常處理中finally的作用Python
- gRPC 中的異常該如何處理?RPC
- Java 中的異常處理機制Java
- 異常處理
- C++ 異常處理機制詳解:輕鬆掌握異常處理技巧C++
- 詳解C#異常處理C#
- Reactor詳解之:異常處理React
- Laravel核心解讀–異常處理Laravel
- Oracle開發基礎-異常處理Oracle
- JSP 異常處理如何處理?JS
- C#中的異常處理機制C#
- Java中的異常處理最佳實踐Java
- React 異常處理React
- JS異常處理JS
- oracle異常處理Oracle
- Python——異常處理Python
- Python異常處理Python
- ThinkPHP 異常處理PHP
- JavaScript 異常處理JavaScript
- JAVA 異常處理Java
- golang - 異常處理Golang
- 異常處理2
- 異常處理1
- Java 異常處理Java
- Abp 異常處理