本文为joshua317原创文章,转载请注明:转载自joshua317博客 SpringBoot统一异常处理 - joshua317的博客
一、背景
在做项目时,会产生各种各样业务异常,大致可以分为下面几类
1. 参数异常:服务端接收客户端参数时,参数不符合规则而产生的问题
2. 数据库异常:服务端和数据库交互时发生的异常
3. 业务异常:系统业务产生的问题
4. 未知异常:不属于以上三种异常的情况
异常根据自己的需要,进行增加,比如服务调用异常,服务错误异常、逻辑业务异常等等
二、解决思路
对项目异常进行分类编码,服务端需要将这些异常信息返回给客户端。 建立全局异常处理类,在类中针对不同类型异常进行返回值处理,包括默认返回结果。 在业务中,不同未知抛出不同异常
三、关键代码
全局异常处理
-
@RestControllerAdvice
-
@Slf4j
-
public
class
GlobalExceptionHandler {
-
-
/**
-
*业务异常
-
*/
-
@ExceptionHandler(BusinessException.class)
-
public RetResult
businessExceptionHandler
(HttpServletRequest request, BusinessException e){
-
if(Objects.nonNull(request)){
-
StringBuffer
requestUrlBuffer
= request.getRequestURL();
-
String
method
= request.getMethod();
-
String
requestUrl
= Objects.isNull(requestUrlBuffer) ? request.getRequestURI() : requestUrlBuffer.toString();
-
log.info(
"BusinessException:{}, \n请求URL: [{}], \n请求方式: [{}]\n", e.getMessage(), requestUrl, method, e);
-
}
-
return ResultUtil.error(e.getCode(), e.getMessage());
-
}
-
-
/**
-
*参数异常
-
*/
-
@ExceptionHandler(ParamException.class)
-
public RetResult
paramExceptionHandler
(HttpServletRequest request, ParamException e) {
-
if (Objects.nonNull(request)) {
-
StringBuffer
requestUrlBuffer
= request.getRequestURL();
-
String
method
= request.getMethod();
-
String
requestUrl
= Objects.isNull(requestUrlBuffer) ? request.getRequestURI() : requestUrlBuffer.toString();
-
log.info(
"ParamException:{}, \n请求URL: [{}], \n请求方式: [{}]\n", e.getMessage(), requestUrl, method, e);
-
}
-
return ResultUtil.error(e.getCode(), e.getMessage());
-
}
-
-
/**
-
*数据库异常
-
*/
-
@ExceptionHandler(DataBaseException.class)
-
public RetResult
databseExceptionHandler
(HttpServletRequest request, DataBaseException e) {
-
if (Objects.nonNull(request)) {
-
StringBuffer
requestUrlBuffer
= request.getRequestURL();
-
String
method
= request.getMethod();
-
String
requestUrl
= Objects.isNull(requestUrlBuffer) ? request.getRequestURI() : requestUrlBuffer.toString();
-
log.info(
"DatabseExceptionHandler{}, \n请求URL: [{}], \n请求方式: [{}]\n", e.getMessage(), requestUrl, method, e);
-
}
-
return ResultUtil.error(e.getCode(), e.getMessage());
-
}
-
-
@ExceptionHandler(RuntimeException.class)
-
public RetResult
runtimeExceptionHandler
(HttpServletRequest request, RuntimeException e){
-
if(Objects.nonNull(request)){
-
StringBuffer
requestUrlBuffer
= request.getRequestURL();
-
String
method
= request.getMethod();
-
String
requestUrl
= Objects.isNull(requestUrlBuffer) ? request.getRequestURI() : requestUrlBuffer.toString();
-
log.error(
"RuntimeException:{}, \n请求URL: [{}], \n请求方式: [{}]\n", e.getMessage(), requestUrl, method, e);
-
}
-
return ResultUtil.error(EnumResultCode.UN_KNOW_ERROR.getCode(), e.getMessage());
-
}
-
-
@ExceptionHandler(Exception.class)
-
public RetResult
exceptionHandler
(HttpServletRequest request, Exception e){
-
if(Objects.nonNull(request)){
-
StringBuffer
requestUrlBuffer
= request.getRequestURL();
-
String
method
= request.getMethod();
-
String
requestUrl
= Objects.isNull(requestUrlBuffer) ? request.getRequestURI() : requestUrlBuffer.toString();
-
log.error(
"Exception:{}, \n请求URL: [{}], \n请求方式: [{}]\n", e.getMessage(), requestUrl, method, e);
-
}
-
return ResultUtil.error(EnumResultCode.SYSTEM_ERROR.getCode(), e.getMessage());
-
}
-
}
四、具体代码
一共有以下几个文件
- ParamException.java
- BusinessException.java
- DataBaseException.java
- GlobalExceptionHandler.java
- EnumResultCode.java
- ResultUtil.java
- RetResult.java
- TestDemoController.java
1.ParamException.java
-
package com.joshua317.share.exceptions;
-
-
import com.joshua317.share.common.enums.
EnumResultCode;
-
import lombok.
Getter;
-
-
/**
-
* 业务异常专用类
-
*/
-
@Getter
-
public
class ParamException extends RuntimeException {
-
-
private
String code;
-
-
private
String message;
-
-
public
ParamException(
String message) {
-
super(message);
-
this.code =
EnumResultCode.
PARAM_ERROR.getCode();
-
this.message = message;
-
}
-
}
2.BusinessException.java
-
package com.joshua317.manager.exce;
-
-
import com.joshua317.share.common.enums.
EnumResultCode;
-
import lombok.
Getter;
-
-
/**
-
* 业务异常专用类
-
*/
-
@Getter
-
public
class BusinessException extends RuntimeException {
-
-
private
String code;
-
-
private
String message;
-
-
public
BusinessException(int code,
String message) {
-
super(message);
-
this.code = code;
-
this.message = message;
-
}
-
-
public
BusinessException(
String message) {
-
super(message);
-
this.code =
EnumResultCode.
BUSINESS_ERROR.getCode();
-
this.message = message;
-
}
-
-
public
BusinessException(
EnumResultCode resultCode) {
-
super(resultCode.getMessage());
-
this.code = resultCode.getCode();
-
this.message = resultCode.getMessage();
-
}
-
}
3.DataBaseException.java
-
package com.joshua317.share.exceptions;
-
-
import com.joshua317.share.common.enums.
EnumResultCode;
-
import lombok.
Getter;
-
-
/**
-
* 业务异常专用类
-
*/
-
@Getter
-
public
class DataBaseException extends RuntimeException {
-
-
private
String code;
-
-
private
String message;
-
-
public
DataBaseException() {
-
super(message);
-
this.code =
EnumResultCode.
DATABASE_ERROR.getCode();
-
this.message =
EnumResultCode.
DATABASE_ERROR.getMessage();
-
}
-
}
4.GlobalExceptionHandler.java
-
package com.joshua317.manager.exce;
-
-
import com.joshua317.lib.response.exception.ApiException;
-
import com.joshua317.share.common.enums.EnumResultCode;
-
import com.joshua317.share.model.bean.RetResult;
-
import com.joshua317.share.utils.ResultUtil;
-
import lombok.extern.slf4j.Slf4j;
-
import org.springframework.web.bind.annotation.ExceptionHandler;
-
import org.springframework.web.bind.annotation.RestControllerAdvice;
-
-
import javax.servlet.http.HttpServletRequest;
-
import java.util.Objects;
-
-
@RestControllerAdvice
-
@Slf4j
-
public
class
GlobalExceptionHandler {
-
-
/**
-
*业务异常
-
*/
-
@ExceptionHandler(BusinessException.class)
-
public RetResult
businessExceptionHandler
(HttpServletRequest request, BusinessException e){
-
if(Objects.nonNull(request)){
-
StringBuffer
requestUrlBuffer
= request.getRequestURL();
-
String
method
= request.getMethod();
-
String
requestUrl
= Objects.isNull(requestUrlBuffer) ? request.getRequestURI() : requestUrlBuffer.toString();
-
log.info(
"BusinessException:{}, \n请求URL: [{}], \n请求方式: [{}]\n", e.getMessage(), requestUrl, method, e);
-
}
-
return ResultUtil.error(e.getCode(), e.getMessage());
-
}
-
-
/**
-
*参数异常
-
*/
-
@ExceptionHandler(ParamException.class)
-
public RetResult
paramExceptionHandler
(HttpServletRequest request, ParamException e) {
-
if (Objects.nonNull(request)) {
-
StringBuffer
requestUrlBuffer
= request.getRequestURL();
-
String
method
= request.getMethod();
-
String
requestUrl
= Objects.isNull(requestUrlBuffer) ? request.getRequestURI() : requestUrlBuffer.toString();
-
log.info(
"ParamException:{}, \n请求URL: [{}], \n请求方式: [{}]\n", e.getMessage(), requestUrl, method, e);
-
}
-
return ResultUtil.error(e.getCode(), e.getMessage());
-
}
-
-
/**
-
*数据库异常
-
*/
-
@ExceptionHandler(DataBaseException.class)
-
public RetResult
databseExceptionHandler
(HttpServletRequest request, DataBaseException e) {
-
if (Objects.nonNull(request)) {
-
StringBuffer
requestUrlBuffer
= request.getRequestURL();
-
String
method
= request.getMethod();
-
String
requestUrl
= Objects.isNull(requestUrlBuffer) ? request.getRequestURI() : requestUrlBuffer.toString();
-
log.info(
"DatabseExceptionHandler{}, \n请求URL: [{}], \n请求方式: [{}]\n", e.getMessage(), requestUrl, method, e);
-
}
-
return ResultUtil.error(e.getCode(), e.getMessage());
-
}
-
-
@ExceptionHandler(RuntimeException.class)
-
public RetResult
runtimeExceptionHandler
(HttpServletRequest request, RuntimeException e){
-
if(Objects.nonNull(request)){
-
StringBuffer
requestUrlBuffer
= request.getRequestURL();
-
String
method
= request.getMethod();
-
String
requestUrl
= Objects.isNull(requestUrlBuffer) ? request.getRequestURI() : requestUrlBuffer.toString();
-
log.error(
"RuntimeException:{}, \n请求URL: [{}], \n请求方式: [{}]\n", e.getMessage(), requestUrl, method, e);
-
}
-
return ResultUtil.error(EnumResultCode.UN_KNOW_ERROR.getCode(), e.getMessage());
-
}
-
-
@ExceptionHandler(Exception.class)
-
public RetResult
exceptionHandler
(HttpServletRequest request, Exception e){
-
if(Objects.nonNull(request)){
-
StringBuffer
requestUrlBuffer
= request.getRequestURL();
-
String
method
= request.getMethod();
-
String
requestUrl
= Objects.isNull(requestUrlBuffer) ? request.getRequestURI() : requestUrlBuffer.toString();
-
log.error(
"Exception:{}, \n请求URL: [{}], \n请求方式: [{}]\n", e.getMessage(), requestUrl, method, e);
-
}
-
return ResultUtil.error(EnumResultCode.SYSTEM_ERROR.getCode(), e.getMessage());
-
}
-
}
5.EnumResultCode.java
-
package com.
joshua317.
manager.
exce;
-
-
import lombok.
Getter;
-
-
@Getter
-
public
enum
EnumResultCode {
-
//成功
-
SUCCESS(
"0",
"成功"),
-
//错误
-
FALSE(
"1",
"错误"),
-
PARAM_ERROR(
"C_1",
"参数异常"),
-
//内部错误
-
BUSINESS_ERROR(
"C_2",
"业务异常"),
-
DATABASE_ERROR(
"SYS_1",
"数据库异常"),
-
//token超时
-
TOKEN_INVALID(
"AUTH_0",
"token无效或已超时");
-
-
private
String code;
-
private
String message;
-
-
EnumResultCode(
String code,
String message) {
-
this.
code = code;
-
this.
message = message;
-
}
-
}
6.ResultUtil.java
-
package com.joshua317.manager.exce;
-
-
import com.google.gson.Gson;
-
import com.google.gson.GsonBuilder;
-
import org.apache.http.HttpStatus;
-
-
import javax.servlet.ServletRequest;
-
import javax.servlet.ServletResponse;
-
import javax.servlet.http.HttpServletRequest;
-
import javax.servlet.http.HttpServletResponse;
-
import java.io.IOException;
-
-
/**
-
* @author joshua317
-
* @Description: 返回结果工具
-
*/
-
public
class
ResultUtil {
-
-
public
static RetResult
success
(Object obj) {
-
RetResult
res
=
new
RetResult();
-
res.setCode(EnumResultCode.SUCCESS.getCode());
-
res.setMsg(EnumResultCode.SUCCESS.getMessage());
-
res.setData(obj);
-
return res;
-
}
-
-
public
static RetResult
success
(String msg) {
-
RetResult
res
=
new
RetResult();
-
res.setCode(EnumResultCode.SUCCESS.getCode());
-
res.setData(
null);
-
res.setMsg(msg);
-
return res;
-
}
-
-
public
static RetResult
success
(Object obj, String msg) {
-
RetResult
res
=
new
RetResult();
-
res.setCode(EnumResultCode.SUCCESS.getCode());
-
res.setMsg(msg);
-
res.setData(obj);
-
return res;
-
}
-
-
public
static RetResult
success
(Integer code, Object obj, String msg) {
-
RetResult
res
=
new
RetResult();
-
res.setCode(code);
-
res.setMsg(msg);
-
res.setData(obj);
-
return res;
-
}
-
-
public
static RetResult
success
(Object obj, long pageTotal) {
-
RetResult
res
=
new
RetResult();
-
res.setCode(EnumResultCode.SUCCESS.getCode());
-
res.setMsg(EnumResultCode.SUCCESS.getMessage());
-
res.setData(obj);
-
res.setPageTotal(pageTotal);
-
return res;
-
}
-
-
-
public
static RetResult
success
(EnumResultCode exceptionCode, Object obj, long pageTotal) {
-
RetResult
res
=
new
RetResult();
-
res.setCode(exceptionCode.getCode());
-
res.setMsg(exceptionCode.getMessage());
-
res.setData(obj);
-
res.setPageTotal(pageTotal);
-
return res;
-
}
-
-
public
static RetResult
success
(Integer code, Object obj, String msg, long pageTotal) {
-
RetResult
res
=
new
RetResult();
-
res.setCode(code);
-
res.setMsg(msg);
-
res.setData(obj);
-
res.setPageTotal(pageTotal);
-
return res;
-
}
-
-
public
static RetResult
success
() {
-
return success(EnumResultCode.SUCCESS.getMessage());
-
}
-
-
-
public
static RetResult
error
(String msg) {
-
RetResult
res
=
new
RetResult();
-
res.setCode(EnumResultCode.SYSTEM_ERROR.getCode());
-
res.setMsg(msg);
-
return res;
-
}
-
-
public
static RetResult
error
(Integer code, String msg) {
-
RetResult
res
=
new
RetResult();
-
res.setCode(code);
-
res.setMsg(msg);
-
return res;
-
}
-
public
static RetResult
error
(EnumResultCode exceptionCode) {
-
RetResult
res
=
new
RetResult();
-
res.setCode(exceptionCode.getCode());
-
res.setMsg(exceptionCode.getMessage());
-
return res;
-
}
-
-
public
static RetResult
error
(Integer code, String msg, Object obj) {
-
RetResult
res
=
new
RetResult();
-
res.setCode(code);
-
res.setData(obj);
-
res.setMsg(msg);
-
return res;
-
}
-
-
public
static RetResult
error
(Integer code, String msg, Object obj, int pageTotal) {
-
RetResult
res
=
new
RetResult();
-
res.setCode(code);
-
res.setData(obj);
-
res.setMsg(msg);
-
res.setPageTotal(pageTotal);
-
return res;
-
}
-
-
public
static HttpServletResponse
getResponse
(ServletRequest request, ServletResponse response, RetResult retResult)
throws IOException {
-
Gson
gson
=
new
GsonBuilder().create();
-
String
resultString
= gson.toJson(retResult);
-
-
HttpServletRequest
httpServletRequest
= (HttpServletRequest) request;
-
HttpServletResponse
httpServletResponse
= (HttpServletResponse) response;
-
httpServletResponse.setHeader(
"Access-control-Allow-Origin", httpServletRequest.getHeader(
"Origin"));
-
httpServletResponse.setHeader(
"Access-Control-Allow-Methods",
"GET,POST,OPTIONS,PUT,DELETE");
-
httpServletResponse.setHeader(
"Access-Control-Allow-Headers", httpServletRequest.getHeader(
"Access-Control-Request-Headers"));
-
httpServletResponse.setCharacterEncoding(
"UTF-8");
-
httpServletResponse.setContentType(
"application/json;charset=UTF-8");
-
httpServletResponse.setStatus(HttpStatus.SC_NON_AUTHORITATIVE_INFORMATION);
-
httpServletResponse.getWriter().write(resultString);
-
-
return httpServletResponse;
-
}
-
}
7.RetResult.java
-
package com.joshua317.manager.exce;
-
-
import lombok.Data;
-
-
/**
-
* @author joshua317
-
* @Description: 权限请求 返回结果
-
*/
-
@Data
-
public
class
RetResult {
-
private String code;
-
private String msg;
-
private Object
data;
-
private long pageTotal;
//分页时:查询数据数量
-
-
public RetResult() {
-
this.code =
"0";
-
this.msg =
"";
-
this.
data =
null;
-
this.pageTotal =
0;
-
}
-
-
/**
-
* 返回状态码、信息、以及数据
-
*/
-
public RetResult(String code, String msg, Object
data) {
-
this.code = code;
-
this.msg = msg;
-
this.
data =
data;
-
this.pageTotal =
0;
-
}
-
-
/**
-
* 返回状态码、信息、以及数据量
-
*/
-
public RetResult(String code, String msg, Object
data, int pageSize) {
-
this.code = code;
-
this.msg = msg;
-
this.
data =
data;
-
this.pageTotal = pageSize;
-
}
-
-
/**
-
* 只返回状态码,以及信息可以用于失败时候来使用
-
*/
-
public RetResult(String code, String msg) {
-
this.code = code;
-
this.msg = msg;
-
this.
data =
null;
-
this.pageTotal =
0;
-
}
-
-
/**
-
* 只返回状态码和数据
-
*/
-
public RetResult(String code, Object
data) {
-
this.code = code;
-
this.msg =
"";
-
this.
data =
data;
-
this.pageTotal =
0;
-
}
-
}
8.TestDemoController.java
-
package com.joshua317.manager.exce;
-
-
import cn.hutool.core.util.StrUtil;
-
import io.swagger.annotations.Api;
-
import io.swagger.annotations.ApiOperation;
-
import org.springframework.web.bind.
annotation.*;
-
-
/*
-
* @Description 测试接口
-
* @Author joshua317
-
**/
-
@Api(value = "测试接口")
-
@RequestMapping("/demo")
-
@RestController
-
public
class
TestDemoController {
-
-
/**
-
* 新增
-
*
-
* @param code 编号
-
* @return
-
*/
-
@ApiOperation(value = "新增")
-
@PostMapping("/save")
-
public RetResult find(
@RequestParam("code") String code) {
-
if (StrUtil.isEmpty(code)) {
-
throw new BusinessException(
"code不能为空");
-
}
-
return ResultUtil.success(
"新增成功");
-
}
-
}
本文为joshua317原创文章,转载请注明:转载自joshua317博客 SpringBoot统一异常处理 - joshua317的博客
转载:https://blog.csdn.net/joshua317/article/details/128259600
查看评论