web项目全局异常处理方案

本文介绍了如何在SpringBoot项目中使用@ControllerAdvice和@ExceptionHandler注解实现全局异常处理,简化控制层异常处理代码,创建RESTful风格的JsonResult返回类型,并自定义异常类。通过示例展示配置和测试结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一. 使用@ControllerAdvice+@ExceptionHandler注解

目的:在控制层不需要再写如下的代码了

try{
	// 业务逻辑
} catch(BusinessException b) {
	// 日志打印
	// 业务异常处理
} catch(Exception e) {
	// 日志打印
	// 非业务异常处理
}
  1. 构建一个springboot项目(引入依赖spring-boot-starter-web)
    启动类如下:
package com.bigzone.springbootdemo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.scheduling.annotation.EnableScheduling;

// 暂不使用数据库, 所以取消数据源自动配置, 不然会报错
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
public class SpringbootDemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(SpringbootDemoApplication.class, args);
    }
}
  1. 编写统一返回值类型JsonResult, 适用restful风格
package com.bigzone.springbootdemo.common;

import java.io.Serializable;

/**
 * @author wangxq
 * @date 2019/10/9
 * 统一返回格式类
 */
public class JsonResult implements Serializable {
    private static final long serialVersionUID = -4917497061692852616L;

    private static final int SUCCESS_CODE = 0;
    private static final int ERROR_CODE = 1;
    private static final String SUCCESS_MSG = "成功";

    private Integer code;
    private String msg;
    private Object data;

    public JsonResult() {
    }

    public JsonResult(Integer code, String msg) {
        this.code = code;
        this.msg = msg;
    }

    public JsonResult(Integer code, String msg, Object data) {
        this.code = code;
        this.msg = msg;
        this.data = data;
    }

    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;
    }

    public Object getData() {
        return data;
    }

    public void setData(Object data) {
        this.data = data;
    }

    public static JsonResult success(Object data){
        return new JsonResult(SUCCESS_CODE, SUCCESS_MSG, data);
    }

    public static JsonResult failure(String msg) {
        return new JsonResult(ERROR_CODE, msg);
    }
}

  1. 编写自定义异常类
package com.bigzone.springbootdemo.exception;

/**
 * @author wangxq
 * @date 2019/10/10
 * 自定义业务异常类
 */
public class BusinessException extends RuntimeException {
    public BusinessException() {
    }

    public BusinessException(String message) {
        super(message);
    }
}
  1. 编写全局异常处理类(@RestControllerAdvice = @ControllerAdvice + @ResponseBody + …)
package com.bigzone.springbootdemo.exception;

import com.bigzone.springbootdemo.common.JsonResult;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @author wangxq
 * @date 2019/10/10
 * 全局异常处理类
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(BusinessException.class)
    public JsonResult businessExceptionHandler(BusinessException b) {
        System.out.println(b.getMessage());
        return JsonResult.failure(b.getMessage());
    }

    @ExceptionHandler(Exception.class)
    public JsonResult exceptionHandler(Exception e) {
        e.printStackTrace();
        return JsonResult.failure("请求失败!");
    }

}
  1. 编写控制层
package com.bigzone.springbootdemo.controller;

import com.bigzone.springbootdemo.common.JsonResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author wangxq
 * @date 2019/10/9
 */
@RestController
@RequestMapping("/test/")
public class TestResultController {

    @GetMapping("getData1")
    public JsonResult getData1() {
        int a = 10/0;
        return JsonResult.success("success");
    }

	@GetMapping("getData2")
    public JsonResult getData2() {
        if (true) {
            throw new BusinessException("业务异常...");
        }
        return JsonResult.success("success");
    }

}
  1. 测试结果

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值