XiaoRuby
2023-08-11 7b09f233bde70508f6db7e08e983e9a2c4bb3e99
framework/src/main/java/com/yuanchu/mom/handler/GlobalExceptionHandler.java
@@ -1,11 +1,15 @@
package com.yuanchu.mom.handler;
import com.yuanchu.mom.exception.MyFileException;
import com.yuanchu.mom.vo.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.fileupload.impl.FileSizeLimitExceededException;
import org.apache.tomcat.util.http.fileupload.impl.SizeLimitExceededException;
import org.springframework.beans.ConversionNotSupportedException;
import org.springframework.beans.TypeMismatchException;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;
@@ -14,6 +18,7 @@
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.multipart.MultipartException;
import javax.servlet.http.HttpServletResponse;
import java.io.FileNotFoundException;
@@ -230,6 +235,35 @@
        return Result.fail(message);
    }
    @Value("${spring.servlet.multipart.max-file-size}")
    private String maxFileSize;
    @Value("${spring.servlet.multipart.max-request-size}")
    private String maxRequestSize;
    /**
     *文件过大报错提示
     */
    @ExceptionHandler({MultipartException.class})
    public Result<?> fileUploadExceptionHandler(MultipartException  e) {
        String msg;
        Throwable rootCause = e.getRootCause();
        if (rootCause instanceof FileSizeLimitExceededException) {
            msg="上传文件过大【单个文件大小不得超过" + maxFileSize + "】";
        }else if(rootCause instanceof SizeLimitExceededException){
            msg="上传文件过大【总上传大小不得超过" + maxRequestSize + "】";
        }else {
            msg="文件上传失败【服务器异常】";
        }
        return Result.fail(msg);
    }
    /** 文件后缀名不通过返回提示 */
    @ExceptionHandler({MyFileException.class})
    public Result<?> myFileException(Exception e) {
        return Result.fail("抱歉不支持【" + e.getMessage() +"】后缀的文件!");
    }
    /** 其他错误 */
    /**
     * 其他错误