SpringMVC統一異常處理(Controller處理)


1、  在一個controller內的統一處理示例

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.ExceptionHandler;

@RestController
public class TestCtl {

    @RequestMapping("/ready")
    public String ready(){
            throw new RuntimeException("ready拋出的異常");
    }
    
    @ExceptionHandler
    public String ExceptionHandler(Exception e) {
            return e.getMessage();
    }
}

請求結果:

也可以自定義Exception,但最好是RuntimeException的子類,以避免“檢查異常”必須被處理而造成代碼冗余;

    @ExceptionHandler是Spring MVC已有的注解,可用於Controller、ControllerAdvice、RestControllerAdvice類的異常處理。

 

2、 使用ControllerAdvice對同一類異常做統一處理示例:

Controller

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class TestCtl {

    @RequestMapping("/ready")
    public String ready(){
            throw new RuntimeException("ready拋出的異常");
    }
}

 統一異常攔截類

import org.springframework.core.annotation.Order;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@Order(0)
@RestControllerAdvice(annotations = RestController.class)
public class RestCtlAdvice {

@ExceptionHandler
@ResponseBody //RestControllerAdvice中無需添加此注解,同RestController
    public String ExceptionHandler(Exception e) {
            return e.getMessage();
    }
}

     最后運行結果同1,RestCtlAdvice會對所有RestController中的異常進行處理,如果是Exception(此可以是自定義的特定異常的精細處理)類型異常,RestCtlAdvice類可以有多處,處理順序按照給定的order來運行。RestController.class也可以替換為Controller.class,則對所有Controller的異常進行攔截。 

     Java 異常體系設計的目的在於通過使用少量代碼,實現大型、健壯、可靠程序。異常處理是 Java 中唯一正式的錯誤報告機制。異常處理機制最大的好處就是降低錯誤代碼處理的復雜程度。

      如果不使用異常,那么就必須在調用點檢查特定的錯誤,並在程序的很多地方去處理它;如果使用異常,那么就不必在方法調用處進行檢查,因為異常機制將保證能夠捕獲這個錯誤。因此只需要在一個地方處理錯誤,這種方式不僅節省代碼,而且把“描述正確執行過程做什么事”和“出了問題怎么辦”相分離。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM