时间的法外狂徒

导航

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
}

 

posted on 2019-08-20 17:36  抄手砚  阅读(1571)  评论(0编辑  收藏  举报