springboot異常處理方式


一、異常處理思路

  異常捕獲的是unchecked型異常,因為checked異常在代碼中年已經處理過,當然是在使用try-catch處理。這里首先使用ExceptionHandler捕獲全局異常,這樣如果是程序中有運行時異常就可以被隨時捕獲到,並將必要信息返回給調用者。對於使用try-catch捕獲的異常,先創建自定義的運行時異常類,然后手動拋出。另外,在service使用unchecked異常可以觸發事務回滾。

二、try-catch手動拋出異常代碼演示

spingboot全局異常創建:

package com.dbzx.exception;

import javax.servlet.http.HttpServletRequest;

import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import com.dbzx.common.ResultModel;


/**
 * 攔截異常后返回json信息,如果需要返回html頁面,需要通過ModelAndView返回
 * @author
 *
 */
@RestControllerAdvice
public class JsonResultExceptionHandler {

    @ExceptionHandler(value = Exception.class)
    public ResultModel defaultErrorHandler(HttpServletRequest req, 
            Exception e) throws Exception {

        e.printStackTrace();
        return ResultModel.errorException("異常信息:"+e.getMessage());
    }
}

自定義異常類:

package com.dbzx.exception;

public class CustomUncheckException extends RuntimeException{

    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    
    public CustomUncheckException() {
        super();
    }
    
    public CustomUncheckException(String msg) {
        super(msg);
    }
    
    public CustomUncheckException(String msg,Throwable cause) {
        super(msg,cause);
    }
    
}

調用代碼:

package com.dbzx.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.dbzx.common.ResultModel;
import com.dbzx.exception.CustomUncheckException;
import com.dbzx.service.UserService;

@RestController
@RequestMapping("dbzx")
public class HelloController {
  
    @Autowired
    UserService userService;
    
    @RequestMapping("/hello")
    public ResultModel hello() {

        try {
            int i = 1 / 0;
        } catch (Exception e) {
            throw new CustomUncheckException(e.getMessage());
        }
        return ResultModel.ok("hello");
    }
}

調用結果:

{
  "status": 555,
  "msg": "異常信息:/ by zero",
  "data": null
}

 


免責聲明!

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



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