在程度开发的过程中,难免会遇到的错误,我们肯定不能一味的使用try…catch来捕捉异常。为了让我们少挨骂,更为了我们的性命照相,我强烈推荐
不要一直使用try…catch来捕捉
异常封装
引入依赖
<!--封装异常要获取http请求-->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.6</version>
</dependency>
常见状态码
因为我们需要对请求时有可能发出的异常进行捕获,正常的请求会返回200的请求状态码,但是如果是非200的请求就会出现其他的状态码,比如说代码一场会出现500,权限不足会出现403等等。。
状态码 | 含义 |
---|---|
200 | 请求成功 |
301 | 资源(网页等)被永久转移到其它URL |
403 | 权限不足 |
404 | 请求的资源(网页等)不存在 |
500 | 内部服务器错误 |
更详细的状态码可以参考:HTTP常见状态码 200 301 302 404 500
引入封装异常类
异常封装要添加四个类,都放在Util包中
由于这四个类较长,为了文章整体的布局更流畅,我把这部分的代码放在文章末尾
异常的引入
代码:
@GetMapping("/users")
@ApiOperation(value = "获取用户列表", notes = "获取所有的user信息")
public Result getUserList() {
List<User> userList = userDao.getUserList();
int i = 1 / 0;
return Result.ok(userList);
}
在没有加这四个类,也就是没有加异常封装之前,我们的请求会直接报错在页面上,或者直接返回500的状态,这样的内容显然不是我们想要的,我们不想让这样的内容被看到,想把500这类的请求统一的封装起来
捕捉异常
如果引入了异常封装,我们就可以将这类异常避免,我们的请求就会返回正常的错误
这个异常捕捉是全局的异常捕捉,如果出现了我们意料之外的异常,就全都会这样返回
自定义抛出异常
如果我们提前知道错误,也可以将这些类型进行避免,也可以返回我们自定义的内容
@GetMapping("/users")
@ApiOperation(value = "获取用户列表", notes = "获取所有的user信息")
public Result getUserList() {
List<User> userList = userDao.getUserList();
try{
int i = 1/0;
}catch (Exception e){
throw new ApplicationException("500","除数为0");
}
return Result.ok(userList);
}
所以,在我们觉得可能会发生异常时,我们就可以将这些内容进行捕捉,然后抛出,我们就可以自定义出现这些异常时返回我们想返回的内容
异常类
关于类中的代码后续会专门出一篇博客来进行讲解(挖坑ing…),敬请期待…
类图
ApplicationException
package com.banana.demo.util.ExceptionUtil;
/**
* ApplicationException异常, 继承自Exception.
*/
@SuppressWarnings("serial")
public class ApplicationException extends BaseException {
private int httpStatus;
private String message;
private String code;
/**
* 返回体
* HttpStatus:500
* {
* "message":"mesage"
* }
*
* @param httpStatus
* @param message
*/
public ApplicationException(int httpStatus, String message) {
super(httpStatus, message);
}
/**
* 返回体
* HttpStatus:500
* {
* "code":"code",
* "message":"mesage"
* }
*
* @param httpStatus
* @param message
*/
public ApplicationException(int httpStatus, String code, String message) {
super(httpStatus, code, message);
}
public ApplicationException(String code, String message) {
super(code, message);
}
/**
* 异常构造函数
*/
public ApplicationException(String message) {
super(message);
}
public ApplicationException(String message, Throwable cause) {
super(message, cause);
}
public ApplicationException(String code,String message, Throwable cause) {
super(message, code, cause);
}
public ApplicationException(int httpStatus, String code, String message, Throwable cause) {
super(httpStatus, code, message, cause);
}
}
BaseException
package com.banana.demo.util.ExceptionUtil;
import org.apache.http.HttpStatus;
import org.springframework.util.StringUtils;
/**
* ApplicationException异常, 继承自Exception.
*/
@SuppressWarnings("serial")
public class BaseException extends RuntimeException {
protected String code = "";
protected int httpStatus = HttpStatus.SC_OK;
public BaseException(int httpStatus,String message) {
super(message);
this.httpStatus = httpStatus;
}
public BaseException(int httpStatus,String code,String message) {
super(message);
this.code = code;
this.httpStatus = httpStatus;
}
public BaseException(int httpStatus,String code,String message,Throwable cause) {
super(ExceptionUtil.joinMsgAndCode(message, code), cause);
this.code = code;
this.httpStatus = httpStatus;
}
/**
* 异常构造函数
*/
public BaseException(String message) {
super(message);
}
public BaseException(String message, Throwable cause) {
super(message, cause);
}
public BaseException(String code, String message) {
super(ExceptionUtil.joinMsgAndCode(code,message));
this.code = code;
}
public BaseException(String message, String code, Throwable cause) {
// super(ExceptionUtil.joinMsgAndCode(message, code), cause);
this.code = code;
}
public final String getCode() {
if (StringUtils.isEmpty(code)) {
return ExceptionUtil.parseCode(super.getMessage());
}
return this.code;
}
public int getHttpStatus(){
return this.httpStatus;
}
}
ExceptionAdvice
package com.banana.demo.util.ExceptionUtil;
import com.banana.demo.util.Result;
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 javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.io.StringWriter;
/**
* 全局异常处理类
*/
@ControllerAdvice
public class ExceptionAdvice {
protected static Logger logger = LoggerFactory.getLogger(ExceptionUtil.class);
/**
* 处理业务异常
* @param rep
* @param e
* @return
*/
@ExceptionHandler({ApplicationException.class})
@ResponseBody
public Result handleApplicationException(HttpServletResponse rep, ApplicationException e) {
if (e.getHttpStatus()!=200) {
rep.setStatus(e.getHttpStatus());
if(e.getCode().isEmpty()|| e.getCode()==null){
return Result.build(1,e.getMessage());
}
}else {
if (e.getCode().isEmpty() || e.getCode() == null) {
return Result.build(1,e.getMessage());
}
}
return Result.build(Integer.valueOf(e.getCode()), e.getMessage());
// TODO: code类型
}
/**
* 处理未知异常
* @param rep
* @param e
* @return
*/
@ExceptionHandler(value =Exception.class)
@ResponseBody
public Result exceptionHandler(HttpServletResponse rep, Exception e){
logger.error("未知异常!原因是:",e);
rep.setStatus(500);
return Result.build(1,"服务器异常,请联系管理员");
}
public static String getStackTrace(Throwable throwable) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
try {
throwable.printStackTrace(pw);
return sw.toString();
} finally {
pw.close();
}
}
}
ExceptionUtil
package com.banana.demo.util.ExceptionUtil;
import com.banana.demo.util.Result;
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 javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.io.StringWriter;
/**
* 全局异常处理类
*/
@ControllerAdvice
public class ExceptionAdvice {
protected static Logger logger = LoggerFactory.getLogger(ExceptionUtil.class);
/**
* 处理业务异常
* @param rep
* @param e
* @return
*/
@ExceptionHandler({ApplicationException.class})
@ResponseBody
public Result handleApplicationException(HttpServletResponse rep, ApplicationException e) {
if (e.getHttpStatus()!=200) {
rep.setStatus(e.getHttpStatus());
if(e.getCode().isEmpty()|| e.getCode()==null){
return Result.build(1,e.getMessage());
}
}else {
if (e.getCode().isEmpty() || e.getCode() == null) {
return Result.build(1,e.getMessage());
}
}
return Result.build(Integer.valueOf(e.getCode()), e.getMessage());
// TODO: code类型
}
/**
* 处理未知异常
* @param rep
* @param e
* @return
*/
@ExceptionHandler(value =Exception.class)
@ResponseBody
public Result exceptionHandler(HttpServletResponse rep, Exception e){
logger.error("未知异常!原因是:",e);
rep.setStatus(500);
return Result.build(1,"服务器异常,请联系管理员");
}
public static String getStackTrace(Throwable throwable) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
try {
throwable.printStackTrace(pw);
return sw.toString();
} finally {
pw.close();
}
}
}
本系列文章
(一) SpringBoot 项目初始化 + 配置swagger页面
(二) SpringBoot 整合 MyBatis-plus