Spring Boot 全局异常处理简单搭建

 项目结构图:

spring boot 项目controller层: 可以看到自定义了除零异常,并没有try{}catch(){}

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * @创建人 fanxuebo
 * @创建时间 2019-10-04 09:51:24 星期五
 * @描述
 */
@RestController
public class TestEurekaClientOneController {

    @Value("${server.port}")
    private String serverPort;

    @Value("${spring.application.name}")
    private String springApplicationName;

    @RequestMapping("hello")
    public String testHelloEureka(@RequestParam(value = "name", defaultValue = "fanxuebo") String name) {
        int errorInt = 1/0;
        return "Hello, " + name + "! My Name: " + springApplicationName + ", My Port:" + serverPort;
    }
}

启动项目浏览器访问情况,返回了错误页面: 

 

下面我们进行全局异常处理: 

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @auther fanxuebo
 * @description 全局的统一异常处理类
 * @Company 
 * @createDate 2019-10-12 14:14:15 星期六
 */
@ControllerAdvice
@ResponseBody
public class RunTimeExceptionHandler {

    @ExceptionHandler(RuntimeException.class)
    public CommonResDto exceptionHandler(RuntimeException e) {
        return new CommonResDto(e.getMessage());
    }
}

再次通过浏览器访问,已将异常捕获。

补上pom依赖和全局异常处理类中的CommonResDto对象。 

pom文件只需引入依赖即可:该处的版本管理在父pom中。

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

下面规范化了公共响应对象,和公共常量对象。省略了get set方法。

import java.io.Serializable;
import java.util.Date;

/**
 * @auther fanxuebo
 * @desc 公共响应对象(针对前端)
 * @Company 
 * @create 2018/11/14 11:10
 */
public class CommonResDto<T> implements Serializable {
    private static final long serialVersionUID = 5098229702138714205L;
    private String resultCode;//响应编码
    private T resultMsg;//响应详细信息
    private Date executeSqlTime;//提取时间(数据库查询时间)
    private T displayStatus;//页面按钮展示

    public CommonResDto() {
    }

    public CommonResDto(T errorResultMsg) {
        this.resultCode = ConstantRes.ERROR_CODE;
        this.resultMsg = errorResultMsg;
    }
}

 

/**
 * @auther fanxuebo
 * @description 公共常量对象
 * @Company 
 * @createDate 2019-10-12 16:23:37 星期六
 */
public class ConstantRes {

    public static final String SUCCESS_CODE = "000000";
    public static final String SUCCESS_MSG = "操作成功";
    public static final String ERROR_CODE = "000001";
}

 

 以上,很简单的一个时间,能够避免开发代码中很多丑陋的try{}catch(){}。配合assert断言效果更佳。全局的异常处理类可以针对业务异常精确分类。

 

感谢你们的阅读!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值