You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

77 lines
2.9 KiB

package com.zh.project0512.utils;
import com.zh.project0512.utils.result.HttpStatusEnum;
import com.zh.project0512.utils.result.Result;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindException;
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 javax.servlet.http.HttpServletRequest;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.ValidationException;
import java.util.stream.Collectors;
/**
* Author: didiplus
* Email: 972479352@qq.com
* CreateTime: 2022/4/24
* Desc: 默认全局异常处理。
*/
@RestControllerAdvice
public class RestExceptionHandler {
/**
* 默认全局异常处理。
* @param e the e
* @return ResultData
*/
@ExceptionHandler(value = {BindException.class, ValidationException.class, MethodArgumentNotValidException.class})
public ResponseEntity<Result<String>> handleValidatedException(Exception e) {
Result<String> result = null;
if (e instanceof MethodArgumentNotValidException) {
MethodArgumentNotValidException ex =(MethodArgumentNotValidException) e;
result = Result.fail(HttpStatusEnum.BAD_REQUEST,
ex.getBindingResult().getAllErrors().stream()
.map(ObjectError::getDefaultMessage)
.collect(Collectors.joining(";"))
);
} else if (e instanceof ConstraintViolationException){
ConstraintViolationException ex = (ConstraintViolationException) e;
result = Result.fail(HttpStatusEnum.BAD_REQUEST,
ex.getConstraintViolations().stream()
.map(ConstraintViolation::getMessage)
.collect(Collectors.joining("; "))
);
}else if (e instanceof BindException) {
BindException ex = (BindException ) e;
result = Result.fail(HttpStatusEnum.BAD_REQUEST,
ex.getAllErrors().stream()
.map(ObjectError::getDefaultMessage)
.collect(Collectors.joining("; "))
);
}
return new ResponseEntity<>(result,HttpStatus.BAD_REQUEST);
}
/**
* 处理自定义的业务异常
* @param req 请求
* @param e 异常
* @return
*/
@ExceptionHandler(value = BizException.class)
@ResponseBody
public Result<String> bizExceptionHandler(HttpServletRequest req, BizException e){
// log.error("发生业务异常!原因是:{}",e.getMessage());
return Result.fail(e.getCode(),e.getMessage());
}
}