package com.whdc.zhdbaqapi.exception; import cn.dev33.satoken.exception.NotLoginException; import com.whdc.zhdbaqapi.utils.ResultJson; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.springframework.dao.DataIntegrityViolationException; import org.springframework.http.HttpStatus; import org.springframework.http.converter.HttpMessageNotReadableException; import org.springframework.validation.BindException; import org.springframework.validation.BindingResult; import org.springframework.validation.FieldError; import org.springframework.validation.ObjectError; import org.springframework.web.HttpMediaTypeNotSupportedException; import org.springframework.web.HttpRequestMethodNotSupportedException; import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.MissingServletRequestParameterException; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestControllerAdvice; import javax.annotation.PostConstruct; import javax.validation.ConstraintViolation; import javax.validation.ConstraintViolationException; import javax.validation.ValidationException; import java.sql.SQLIntegrityConstraintViolationException; import java.util.Set; /** * @author 李赛 * @date 2022-06-26 10:58 */ @RestControllerAdvice @Slf4j public class MyExceptionHandler { @PostConstruct public void init() { } /** * 保存错误日志 * * @param e 错误内容 */ private void saveLogs(Exception e) { } /** * 400 - Bad Request */ @ResponseStatus(HttpStatus.OK) @ExceptionHandler(MissingServletRequestParameterException.class) public ResultJson handleMissingServletRequestParameterException(MissingServletRequestParameterException e) { log.error("缺少请求参数", e); return ResultJson.error(ResultJson.PARAM_ERROR, "缺少请求参数"); } /** * 400 - Bad Request */ @ResponseStatus(HttpStatus.OK) @ExceptionHandler(HttpMessageNotReadableException.class) public ResultJson handleHttpMessageNotReadableException(HttpMessageNotReadableException e) { log.error("缺少请求参数", e); return ResultJson.error(ResultJson.PARAM_ERROR, "参数格式错误。使用 json 格式字符串传递参数"); } /** * 400 - Bad Request--------------------- */ @ResponseStatus(HttpStatus.OK) @ExceptionHandler(MethodArgumentNotValidException.class) public ResultJson handleMethodArgumentNotValidException(MethodArgumentNotValidException e) { try { // log.error("参数验证失败 " + e.getMessage(), e); BindingResult result = e.getBindingResult(); if (result.getErrorCount() > 0) { StringBuffer strbuf = new StringBuffer(); for (ObjectError err : result.getAllErrors()) { if (strbuf.length() > 0) { strbuf.append(";"); } strbuf.append(err.getDefaultMessage()); } return ResultJson.error(ResultJson.PARAM_ERROR, "参数验证失败:" + strbuf.toString()); } return ResultJson.error(ResultJson.PARAM_ERROR, "参数验证失败"); } catch (Exception err) { return ResultJson.error(ResultJson.PARAM_ERROR, "参数验证失败," + err.getMessage()); } } /** * 400 - Bad Request */ @ResponseStatus(HttpStatus.OK) @ExceptionHandler(BindException.class) public ResultJson handleBindException(BindException e) { BindingResult result = e.getBindingResult(); FieldError error = result.getFieldError(); String field = error.getField(); String code = error.getDefaultMessage(); String message = String.format("%s:%s", field, code); log.error("参数绑定失败", message); return ResultJson.error(ResultJson.PARAM_ERROR, "参数绑定失败," + message); } /** * 400 - Bad Request */ @ResponseStatus(HttpStatus.OK) @ExceptionHandler(ConstraintViolationException.class) public ResultJson handleServiceException(ConstraintViolationException e) { Set> violations = e.getConstraintViolations(); ConstraintViolation violation = violations.iterator().next(); String message = violation.getMessage(); log.error("参数验证失败 " + message, e); return ResultJson.error(ResultJson.PARAM_ERROR, "参数验证失败," + message); } /** * 400 - Bad Request */ @ResponseStatus(HttpStatus.OK) @ExceptionHandler(ValidationException.class) public ResultJson handleValidationException(ValidationException e) { log.error("参数验证失败 " + e.getMessage(), e); return ResultJson.error(ResultJson.PARAM_ERROR, "参数验证失败"); } /** * 405 - Method Not Allowed */ @ResponseStatus(HttpStatus.OK) @ExceptionHandler(HttpRequestMethodNotSupportedException.class) public ResultJson handleHttpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e) { log.error("不支持当前请求方法", e.getMessage()); return ResultJson.error(ResultJson.METHOD_NOT_ALLOWED, "不支持当前请求方法"); } /** * 415 - Unsupported Media Type */ @ResponseStatus(HttpStatus.OK) @ExceptionHandler(HttpMediaTypeNotSupportedException.class) public ResultJson handleHttpMediaTypeNotSupportedException(Exception e) { log.error("不支持当前媒体类型", e.getMessage()); return ResultJson.error(ResultJson.NSUPPORTED_MEDIA_TYPE, "不支持当前媒体类型"); } /** * 操作数据库出现异常:名称重复,外键关联 */ @ResponseStatus(HttpStatus.OK) @ExceptionHandler(DataIntegrityViolationException.class) public ResultJson handleException(DataIntegrityViolationException e) { log.error("操作数据库出现异常: ", e); return ResultJson.error(ResultJson.FAIL, "操作数据库出现异常"); } /** * 通用异常 */ @ResponseStatus(HttpStatus.OK) @ExceptionHandler(Exception.class) public ResultJson handleException(Exception e) { log.error("通用异常:" + e.getMessage(), e); if (e instanceof SQLIntegrityConstraintViolationException) { return ResultJson.error(ResultJson.FAIL, "数据库主键冲突,请联系管理员"); } else if (e instanceof org.springframework.web.servlet.NoHandlerFoundException) { return ResultJson.error(ResultJson.FAIL, "找不到资源"); } return ResultJson.error(ResultJson.SERVER_ERROR, "内部服务器错误"); } /** * 500 - Internal Server Error */ @ResponseStatus(HttpStatus.OK) @ExceptionHandler(MyException.class) public ResultJson handleServiceException(MyException e) { log.error("业务逻辑异常", e); //RetryableException 无法单独捕获处理,只能简单处理一下返回值 String msg = e.getMsg(); if (StringUtils.isNotBlank(e.getMsg()) && e.getMsg().startsWith("Connection refused: connect executing POST")) { msg = "连接被拒绝"; } return ResultJson.error(ResultJson.FAIL, msg); } @ResponseStatus(HttpStatus.OK) @ExceptionHandler(NotLoginException.class) public ResultJson handleNotLoginException(NotLoginException e) { log.error("业务逻辑异常", e); return ResultJson.error(ResultJson.UNAUTHORIZED, e.getMessage()); } }