项目结构图:
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断言效果更佳。全局的异常处理类可以针对业务异常精确分类。
感谢你们的阅读!