springboot通過aop處理拋出的異常exception


寫一個配置類攔截所有Exception

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

@ControllerAdvice
public class ExceptionCatch {

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public ResponseResult ExceptionHandle(Exception e) {
        e.printStackTrace();
        return ResponseResult.error("錯誤信息:"+e.getMessage());  // ResponseResult為我們自己封閉的實體類
    }
}

 

攔截指定的異常用以下的方法(自定義的異常)

@ExceptionHandler(MyException.class)
@ResponseBody
public ResponseResult ExceptionHandle2(MyException e) {
    final ResponseResult responseResult = new ResponseResult();
    responseResult.setCode(e.getStatus().toString());
    responseResult.setMessage(e.getMessage());
    return responseResult;
}

 


免責聲明!

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



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