全部try catch處理,全局異常


是否在寫代碼的時候遇到過這樣一種情況,蠻項目寫的都是try catch,尤其是controller,本來就是一個簡單的sellect,寫了賊多的代碼.

是不是這個時候就想要一個全局的異常處理的機制來處理,是不是第一靈感就會想到切面.

下面來記錄下全局異常捕獲的方法

package com.example.demo11;

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

/**
 * @author :szy
 * @title: HelloController
 * @projectName demo11
 * @description: TODO
 * @date 2020/10/30-11:40
 */
@RestController
public class HelloController {
    @GetMapping("/hello")
    public String hello(){

        String val ="10-1";
        //異常
        Integer.valueOf(val);

        return "hello world";
    }
}

異常捕獲代碼

package com.example.demo11;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author :szy
 * @title: UnifiedExceptionHandler
 * @projectName demo11
 * @description: TODO
 * @date 2020/10/30-11:50
 */
@Component
@ControllerAdvice
public class UnifiedExceptionHandler {

    private Logger log = LoggerFactory.getLogger(UnifiedExceptionHandler.class);

    /**
     * 自定義異常
     * @param e 異常
     * @return 異常結果
     */
    @ExceptionHandler(value = NumberFormatException.class)
    @ResponseBody
    public String handleNumberFormatException(NumberFormatException e) {
        log.error(e.getMessage(), e);
        return "轉換錯誤";
    }



    /**
     * 全局異常處理
     * @param e 異常
     * @return 異常結果
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public String handleBaseException(Exception e) {
        log.error(e.getMessage(), e);
        return "error 0000";
    }

}

重點:controller連不要寫try cath ,不然不會被最頂層捕獲

運行的結果:

 


免責聲明!

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



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