淡语

导航

springboot项目添加全局异常

1.新建业务异常类BusinessException.java

package com.zbbz.common.exception;

/**
 * 业务异常
 * 
 * @author danyu
 */
public class BusinessException extends RuntimeException
{
    private static final long serialVersionUID = 1L;

    private Integer code;

    private String message;

    public BusinessException(String message)
    {
        this.message = message;
    }

    public BusinessException(String message, Integer code)
    {
        this.message = message;
        this.code = code;
    }

    public BusinessException(String message, Throwable e)
    {
        super(message, e);
        this.message = message;
    }

    @Override
    public String getMessage()
    {
        return message;
    }

    public Integer getCode()
    {
        return code;
    }
}

 2.添加全局异常类GlobalExceptionHandler.java

package com.zbbz.framework.web.exception;

import com.zbbz.common.core.domain.AjaxResult;
import com.zbbz.common.exception.BusinessException;
import com.zbbz.common.exception.UtilException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

//@ControllerAdvice 该注解定义全局异常处理类
@ControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 所有除捕捉之外的所有异常
     * @param e
     * @return
     */
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public AjaxResult handleException(Exception e)
    {
        e.printStackTrace();
        return AjaxResult.error(e.getMessage());
    }

    /**
     * 业务异常
     */
    @ExceptionHandler(BusinessException.class)
    @ResponseBody
    public AjaxResult businessException(BusinessException e)
    {
        if (e.getCode()==null)
        {
            return AjaxResult.error(e.getMessage());
        }
        return AjaxResult.error(e.getCode(), e.getMessage());
    }

    /**
     * 工具类异常
     */
    @ExceptionHandler(UtilException.class)
    @ResponseBody
    public AjaxResult businessException(UtilException e)
    {
        return AjaxResult.error(e.getMessage());
    }

}

 3.控制器抛出异常

package com.zbbz.web.controller;

import com.zbbz.common.core.domain.AjaxResult;
import com.zbbz.common.exception.BusinessException;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author danyu
 * @date 2020/01/01
 */
@RestController
@RequestMapping("/web")
public class WebController {

    @GetMapping("/test")
    public String test() {
        return "访问成功";
    }

    @GetMapping("/body")
    public AjaxResult body() {
        throw new BusinessException("业务异常");
        //return AjaxResult.success("成功了");
    }

}

 

posted on 2021-01-12 14:09  object360  阅读(225)  评论(0编辑  收藏  举报