Skip to content

Commit

Permalink
统一异常及异常优化方案
Browse files Browse the repository at this point in the history
  • Loading branch information
gaoguanqi committed Apr 24, 2021
1 parent c83a151 commit 21aca0e
Show file tree
Hide file tree
Showing 6 changed files with 256 additions and 1 deletion.
5 changes: 5 additions & 0 deletions guigu-common/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -24,5 +24,10 @@
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<!-- 封装统一异常 处理jdbc异常-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
</dependency>
</dependencies>
</project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
package com.atguigu.common.exception;

import com.atguigu.common.result.ResponseEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

/**
* 异常处理优化方案
* 断言优化
* 程序中可使用断言进行代码优化手段,抛出自定义异常
* 其目的是可将抛出的异常分类,达到观察及追踪程序异常的原因
*/
@Slf4j
public class Assert {

/**
* 断言对象不为空
* obj 为空则抛异常
* @param obj
* @param responseEnum
*/
public static void notNull(Object obj, ResponseEnum responseEnum){
if(obj == null){
log.info("obj is null.....................");
throw new BusinessException(responseEnum);
}
}


/**
* 断言对象为空
* 如果对象obj不为空,则抛出异常
* @param object
* @param responseEnum
*/
public static void isNull(Object object, ResponseEnum responseEnum) {
if (object != null) {
log.info("obj is not null......");
throw new BusinessException(responseEnum);
}
}

/**
* 断言表达式为真
* 如果不为真,则抛出异常
*
* @param expression 是否成功
*/
public static void isTrue(boolean expression, ResponseEnum responseEnum) {
if (!expression) {
log.info("fail...............");
throw new BusinessException(responseEnum);
}
}

/**
* 断言两个对象不相等
* 如果相等,则抛出异常
* @param m1
* @param m2
* @param responseEnum
*/
public static void notEquals(Object m1, Object m2, ResponseEnum responseEnum) {
if (m1.equals(m2)) {
log.info("equals...............");
throw new BusinessException(responseEnum);
}
}

/**
* 断言两个对象相等
* 如果不相等,则抛出异常
* @param m1
* @param m2
* @param responseEnum
*/
public static void equals(Object m1, Object m2, ResponseEnum responseEnum) {
if (!m1.equals(m2)) {
log.info("not equals...............");
throw new BusinessException(responseEnum);
}
}

/**
* 断言参数不为空
* 如果为空,则抛出异常
* @param s
* @param responseEnum
*/
public static void notEmpty(String s, ResponseEnum responseEnum) {
if (StringUtils.isEmpty(s)) {
log.info("is empty...............");
throw new BusinessException(responseEnum);
}
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
package com.atguigu.common.exception;

import com.atguigu.common.result.ResponseEnum;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@NoArgsConstructor
public class BusinessException extends RuntimeException{

//错误码
private Integer code;
//错误消息
private String message;

/**
*
* @param message 错误消息
*/
public BusinessException(String message) {
this.message = message;
}

/**
*
* @param message 错误消息
* @param code 错误码
*/
public BusinessException(String message, Integer code) {
this.message = message;
this.code = code;
}

/**
*
* @param message 错误消息
* @param code 错误码
* @param cause 原始异常对象
*/
public BusinessException(String message, Integer code, Throwable cause) {
super(cause);
this.message = message;
this.code = code;
}

/**
*
* @param resultCodeEnum 接收枚举类型
*/
public BusinessException(ResponseEnum resultCodeEnum) {
this.message = resultCodeEnum.getMessage();
this.code = resultCodeEnum.getCode();
}

/**
*
* @param resultCodeEnum 接收枚举类型
* @param cause 原始异常对象
*/
public BusinessException(ResponseEnum resultCodeEnum, Throwable cause) {
super(cause);
this.message = resultCodeEnum.getMessage();
this.code = resultCodeEnum.getCode();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
package com.atguigu.common.exception;

import com.atguigu.common.result.R;
import com.atguigu.common.result.ResponseEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.ConversionNotSupportedException;
import org.springframework.beans.TypeMismatchException;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.jdbc.BadSqlGrammarException;
import org.springframework.web.HttpMediaTypeNotAcceptableException;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingPathVariableException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.async.AsyncRequestTimeoutException;
import org.springframework.web.multipart.support.MissingServletRequestPartException;
import org.springframework.web.servlet.NoHandlerFoundException;

/**
* 统一异常处理
* RestControllerAdvice 注解可自动捕获全局异常
* 本类必须可被 SpringBootApplication 扫描到,
*
*/
@Slf4j
@RestControllerAdvice
public class UnifiedExceptionHandler {

@ExceptionHandler(value = Exception.class)
public R handleException(Exception e){
log.error(e.getMessage(), e);
return R.error();
}

@ExceptionHandler(value = BadSqlGrammarException.class)
public R handleException(BadSqlGrammarException e){
log.error(e.getMessage(), e);
return R.setResult(ResponseEnum.BAD_SQL_GRAMMAR_ERROR);
}


@ExceptionHandler(value = BusinessException.class)
public R handleException(BusinessException e){
log.error(e.getMessage(), e);
return R.error().message(e.getMessage()).code(e.getCode());
}

/**
* Controller上一层相关异常
*/
@ExceptionHandler({
NoHandlerFoundException.class,
HttpRequestMethodNotSupportedException.class,
HttpMediaTypeNotSupportedException.class,
MissingPathVariableException.class,
MissingServletRequestParameterException.class,
TypeMismatchException.class,
HttpMessageNotReadableException.class,
HttpMessageNotWritableException.class,
MethodArgumentNotValidException.class,
HttpMediaTypeNotAcceptableException.class,
ServletRequestBindingException.class,
ConversionNotSupportedException.class,
MissingServletRequestPartException.class,
AsyncRequestTimeoutException.class
})
public R handleServletException(Exception e) {
log.error(e.getMessage(), e);
//SERVLET_ERROR(-102, "servlet请求异常"),
return R.error().message(ResponseEnum.SERVLET_ERROR.getMessage()).code(ResponseEnum.SERVLET_ERROR.getCode());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
import org.springframework.context.annotation.ComponentScan;

@SpringBootApplication
@ComponentScan({"com.atguigu.srb"})
@ComponentScan({"com.atguigu.srb","com.atguigu.common"})
public class ServiceCoreApplication {

public static void main(String[] args) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,10 @@


import ch.qos.logback.core.joran.util.beans.BeanUtil;
import com.atguigu.common.exception.Assert;
import com.atguigu.common.exception.BusinessException;
import com.atguigu.common.result.R;
import com.atguigu.common.result.ResponseEnum;
import com.atguigu.srb.core.pojo.entity.IntegralGrade;
import com.atguigu.srb.core.service.IntegralGradeService;
import com.baomidou.mybatisplus.core.toolkit.BeanUtils;
Expand Down Expand Up @@ -45,6 +48,7 @@ public R listAll(){
public R removeById(
@ApiParam(value = "数据id", example = "1",required = true)
@PathVariable Long id){

boolean result = integralGradeService.removeById(id);
if(result){
return R.ok().message("删除成功");
Expand All @@ -58,6 +62,13 @@ public R removeById(
public R save(
@ApiParam(value = "积分等级对象",required = true)
@RequestBody IntegralGrade integralGrade){

//使用自定义异常判断数据
// if(integralGrade.getBorrowAmount() == null){
// throw new BusinessException(ResponseEnum.BORROW_AMOUNT_NULL_ERROR);
// }
Assert.notNull(integralGrade.getBorrowAmount(), ResponseEnum.BORROW_AMOUNT_NULL_ERROR);

boolean result = integralGradeService.save(integralGrade);
if(result){
return R.ok().message("保存成功");
Expand Down

0 comments on commit 21aca0e

Please sign in to comment.