package com.cl.common.handler;
|
|
|
|
import com.cl.common.constant.MessageConstant;
|
import com.cl.common.exception.BaseException;
|
import com.cl.common.exception.user.InterceptorException;
|
import com.cl.common.result.Result;
|
import lombok.extern.slf4j.Slf4j;
|
import org.springframework.validation.ObjectError;
|
import org.springframework.web.bind.MethodArgumentNotValidException;
|
import org.springframework.web.bind.annotation.ExceptionHandler;
|
import org.springframework.web.bind.annotation.ResponseBody;
|
import org.springframework.web.bind.annotation.RestControllerAdvice;
|
|
import java.sql.SQLIntegrityConstraintViolationException;
|
|
/**
|
* 全局异常处理器,处理项目中抛出的业务异常
|
*/
|
@RestControllerAdvice
|
@Slf4j
|
public class GlobalExceptionHandler {
|
|
|
/**
|
* 捕获业务异常
|
* @param ex
|
* @return
|
*/
|
@ExceptionHandler
|
public Result exceptionHandler(BaseException ex){
|
log.error("异常信息:{}", ex.getMessage());
|
return Result.error(ex.getMessage());
|
}
|
|
/**
|
* 捕获业务异常
|
* @param ex
|
* @return
|
*/
|
@ExceptionHandler
|
public Result loginHandler(InterceptorException ex){
|
log.error("异常信息:{}", ex.getMessage());
|
return Result.error(401,ex.getMessage());
|
}
|
|
|
/**
|
* 数据校验异常
|
* @param e
|
* @return
|
*/
|
@ExceptionHandler(value = MethodArgumentNotValidException.class)
|
public Result errorHandler(MethodArgumentNotValidException e){
|
// BindingResult bindingResult=exception.getBindingResult();
|
String message="";
|
// String message=bindingResult.getAllErrors().stream().map(DefaultMessageSourceResolvable::getDefaultMessage).collect(Collectors.joining());
|
// for(ObjectError s:e.getAllErrors()){
|
// message+=s.getDefaultMessage();
|
// break;
|
// }
|
message= String.valueOf(e.getAllErrors().get(0).getDefaultMessage());
|
|
log.info("数据校验错误:{}",message);
|
return Result.error(message);
|
}
|
|
/**
|
* 处理sql异常
|
* @param ex
|
* @return
|
*/
|
@ExceptionHandler
|
public Result exceptionHandler(SQLIntegrityConstraintViolationException ex){
|
|
//Duplicate entry 'zhangsan' for key 'idx_username'
|
String message = ex.getMessage();
|
if (message.contains("Duplicate entry")){
|
String[] split = message.split(" ");
|
String username=split[2];
|
String msg=username+ MessageConstant.ALREADY_EXISTS;
|
return Result.error(msg);
|
}else {
|
log.error(message,ex);
|
return Result.error(MessageConstant.UNKNOWN_ERROR);
|
}
|
|
}
|
|
|
|
|
}
|