Springboot全局异常处理Demo

通用信息返回json类

package com.example.demo.exception;

/**
 * @author shi
 * @created 2019/11/15
 */
public class GeneralResponse {

    private Integer code;
    private String msg;
    
    public Integer getCode() {
        return code;
    }
    public void setCode(Integer code) {
        this.code = code;
    }
    public String getMsg() {
        return msg;
    }
    public void setMsg(String msg) {
        this.msg = msg;
    }
    private GeneralResponse(Integer code, String msg) {
        this.code = code;
        this.msg = msg;
    }
    
    public static GeneralResponse success(String msg){
        return new GeneralResponse(1,msg);
    }
    public static GeneralResponse error(String msg){
        return new GeneralResponse(4,msg);
    }
}

自定义异常类

package com.example.demo.exception;

/**
 * @author shi
 * @created 2019/11/15
 * 自定义异常类
 */
public class CustomException extends RuntimeException {
    public CustomException(String message) {
        super(message);
    }
}

全局异常处理器

package com.example.demo.exception;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author shi
 * @created 2019/11/15
 * 全局异常处理器
 */

//component,如果全部是json返回可用@RestControllerAdvice代替
@ControllerAdvice
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {

    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ResponseBody
    @ExceptionHandler(CustomException.class)//捕获目标异常类
    public GeneralResponse customExceptionHandler(HttpServletRequest request, final Exception e, HttpServletResponse response){

        logger.error("CustomException catch!");
        logger.error("first param",e);//异常放第二个参数才能打印异常栈
        return GeneralResponse.error(e.getMessage());//将异常的信息传入返回的信息
    }

    //此处返回自定义异常结果页面
    @ExceptionHandler(RuntimeException.class)
    public ModelAndView customExceptionHandler2(HttpServletRequest request, final Exception e, HttpServletResponse response){

        logger.error("CustomException catch!");
        logger.error("first param",e);
        ModelAndView mav = new ModelAndView();
        mav.addObject("errorMsg",e.getMessage());
        mav.setViewName("error.html");
        return mav;
    }
}

controller测试

	@RequestMapping("/exception")
    public String testException(){
        if(1==1)
            throw new CustomException("千万不能让1==1");
        return "error!";
    }

结果:

{“code”:4,“msg”:“千万不能让1==1”}

日志:

2019-11-15 18:01:25.715 ERROR 3934 — [nio-8081-exec-7] c.e.d.exception.GlobalExceptionHandler : CustomException catch!
2019-11-15 18:01:25.722 ERROR 3934 — [nio-8081-exec-7] c.e.d.exception.GlobalExceptionHandler : first param

com.example.demo.exception.CustomException: 千万不能让1==1
at sun.reflect.GeneratedConstructorAccessor114.newInstance(Unknown Source) ~[na:na]
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45005) ~[na:1.8.0_171]
at com.zeroturnaround.jrebelbase.facade.Forward.invokeNewConstructor(SourceFile:149) ~[na:1.8.0_171]
at com.example.demo.exception.CustomException.(CustomException.java:65534) ~[classes/:na]
at com.example.demo.controller.TestController.testException(TestController.java:43) ~[classes/:na]
at sun.reflect.GeneratedMethodAccessor86.invoke(Unknown Source) ~[na:na]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:45005) ~[na:1.8.0_171]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_171]

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值