Explorar o código

修改全局异常处理

杨杰 %!s(int64=6) %!d(string=hai) anos
pai
achega
8815b8b1ca

+ 0 - 62
src/main/java/com/llisoft/pay/config/ErrorConfig.java

@@ -1,62 +0,0 @@
-package com.llisoft.pay.config;
-
-import java.util.Objects;
-
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.boot.web.servlet.error.ErrorController;
-import org.springframework.web.bind.annotation.RequestMapping;
-import org.springframework.web.bind.annotation.RestController;
-
-import com.llisoft.common.constant.CodeEnum;
-import com.llisoft.common.vo.ResponseVo;
-
-/**
- * 框架级异常处理, 覆盖默认/error
- * 根据错误信息返回具体的json结果
- * 模仿 org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController
- * @author YangJie [2018年12月27日]
- */
-@RestController
-public class ErrorConfig implements ErrorController {
-	
-	private Logger logger = LoggerFactory.getLogger(ErrorConfig.class);
-	
-
-	@RequestMapping("/error")
-	public ResponseVo<Object> error(HttpServletRequest request, HttpServletResponse response) {
-		response.setStatus(200); // 状态码全部200
-		Object statusCode = request.getAttribute("javax.servlet.error.status_code");
-		if(Objects.nonNull(statusCode) && statusCode instanceof Integer) {
-			int code = Integer.parseInt(statusCode.toString());
-			if(code == CodeEnum.C400.getCode()) {
-				logger.error("/error: {}", CodeEnum.C400.getMsg());
-				return ResponseVo.build(CodeEnum.C400);
-			}else if (code == CodeEnum.C401.getCode()) {
-				logger.error("/error: {}", CodeEnum.C401.getMsg());
-				return ResponseVo.build(CodeEnum.C401);
-			}else if (code == CodeEnum.C402.getCode()) {
-				logger.error("/error: {}", CodeEnum.C402.getMsg());
-				return ResponseVo.build(CodeEnum.C402);
-			}else if (code == CodeEnum.C403.getCode()) {
-				logger.error("/error: {}", CodeEnum.C403.getMsg());
-				return ResponseVo.build(CodeEnum.C403);
-			}else if (code == CodeEnum.C404.getCode()) {
-				logger.error("/error: {}", CodeEnum.C404.getMsg());
-				return ResponseVo.build(CodeEnum.C404);
-			}
-		}
-		logger.error("/error: {}", CodeEnum.C500.getMsg());
-		return ResponseVo.build(CodeEnum.C500);
-	}
-
-	
-	@Override
-	public String getErrorPath() {
-		return "/error";
-	}
-	
-}

+ 0 - 93
src/main/java/com/llisoft/pay/config/ExceptionConfig.java

@@ -1,93 +0,0 @@
-package com.llisoft.pay.config;
-
-import java.nio.file.AccessDeniedException;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.beans.factory.annotation.Value;
-import org.springframework.http.converter.HttpMessageNotReadableException;
-import org.springframework.web.bind.MethodArgumentNotValidException;
-import org.springframework.web.bind.annotation.ControllerAdvice;
-import org.springframework.web.bind.annotation.ExceptionHandler;
-import org.springframework.web.bind.annotation.ResponseBody;
-
-import com.llisoft.common.constant.CodeEnum;
-import com.llisoft.common.exception.MtaException;
-import com.llisoft.common.vo.MailSendVo;
-import com.llisoft.common.vo.ResponseVo;
-import com.llisoft.pay.service.feign.FeignMailService;
-
-/**
- * 统一处理业务异常 controller
- * @author YangJie [2018年12月26日]
- */
-@ControllerAdvice
-public class ExceptionConfig {
-	
-	private Logger logger = LoggerFactory.getLogger(ExceptionConfig.class);
-	
-	@Value("${spring.application.name}")
-	private String application;
-	
-	@Autowired
-	private FeignMailService feignMailService;
-	
-
-    /**
-     * 入参空
-     * @param exception
-     * @return
-     */
-    @ExceptionHandler(HttpMessageNotReadableException.class)
-    public @ResponseBody ResponseVo<String> exception(HttpMessageNotReadableException exception){
-    	logger.warn("入参异常: {}", exception.getMessage());
-        return ResponseVo.build(CodeEnum.C400);
-    }
-    
-    /**
-     * 入参检验失败
-     * @param exception
-     * @return
-     */
-    @ExceptionHandler(MethodArgumentNotValidException.class)
-    public @ResponseBody ResponseVo<String> exception(MethodArgumentNotValidException exception){
-    	logger.warn("入参异常: {}", exception.getMessage());
-    	return ResponseVo.build(CodeEnum.C400.getCode(), exception.getBindingResult().getFieldError().getDefaultMessage());
-    }
-    
-    /**
-     * 无权访问
-     * @param exception
-     * @return
-     */
-    @ExceptionHandler(AccessDeniedException.class)
-    public @ResponseBody ResponseVo<String> exception(AccessDeniedException exception){
-    	logger.warn("无权访问: {}", exception.getMessage());
-    	return ResponseVo.build(CodeEnum.C403);
-    }
-	
-    /**
-     * 业务异常
-     * @param exception
-     * @return
-     */
-    @ExceptionHandler(MtaException.class)
-    public @ResponseBody ResponseVo<String> exception(MtaException exception){
-    	logger.warn("业务异常: {}", exception.getMessage());
-    	return ResponseVo.build(CodeEnum.FAIL.getCode(), exception.getMessage());
-    }
-    
-    /**
-     * 默认异常
-     * @param exception
-     * @return
-     */
-    @ExceptionHandler(Exception.class)
-    public @ResponseBody ResponseVo<String> exception(Exception exception){
-    	logger.error("服务异常", exception);
-    	feignMailService.send(MailSendVo.build("【" + application + "】服务异常", exception));
-    	return ResponseVo.build(CodeEnum.C500);
-    }
-    
-}

+ 0 - 27
src/main/java/com/llisoft/pay/config/SpringMvcConfig.java

@@ -1,27 +0,0 @@
-package com.llisoft.pay.config;
-
-import org.springframework.context.annotation.Configuration;
-import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
-import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
-
-/**
- * 配置spring mvc
- * @author YangJie [2018年12月25日]
- */
-@Configuration
-public class SpringMvcConfig implements WebMvcConfigurer {
-	
-	@Override // 默认首页
-	public void addViewControllers(ViewControllerRegistry registry) {
-			registry.addRedirectViewController("/", "/swagger-ui.html");
-	}
-
-//	@Override // 跨域配置
-//	public void addCorsMappings(CorsRegistry registry) {
-//    	registry.addMapping("/**")
-//	        .allowedOrigins("*")
-//	        .allowedHeaders("*")
-//	        .allowedMethods("POST", "OPTIONS");
-//	}
-	
-}

+ 0 - 36
src/main/java/com/llisoft/pay/config/SwaggerConfig.java

@@ -1,36 +0,0 @@
-package com.llisoft.pay.config;
-
-import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
-import org.springframework.context.annotation.Bean;
-import org.springframework.context.annotation.Configuration;
-
-import com.google.common.base.Predicates;
-
-import springfox.documentation.builders.ApiInfoBuilder;
-import springfox.documentation.builders.PathSelectors;
-import springfox.documentation.spi.DocumentationType;
-import springfox.documentation.spring.web.plugins.Docket;
-import springfox.documentation.swagger2.annotations.EnableSwagger2;
-
-/**
- * swagger配置
- * @author YangJie [2018年12月25日]
- */
-@Configuration
-@EnableSwagger2 // 启用swagger
-@ConditionalOnProperty(name="mta.debug", havingValue="true") // 仅开发启用
-public class SwaggerConfig {
-
-	@Bean  
-	public Docket docket() {  
-		return new Docket(DocumentationType.SWAGGER_2)
-			.apiInfo(new ApiInfoBuilder().title("支付服务API【pay】").version("v1.0.0").build())
-			.directModelSubstitute(byte.class, int.class) //修正byte转string的Bug
-			.select()
-			// 文档中需要屏蔽的接口
-			.paths(Predicates.not(PathSelectors.regex("/error.*")))
-			.paths(Predicates.not(PathSelectors.regex("/actuator.*")))
-			.build();
-	}  
-	
-}

+ 39 - 34
src/main/resources/application.yml

@@ -1,7 +1,3 @@
-##服务配置
-server:
-  port: 8003 #监听端口
-  
 ##自定义配置
 mta: 
   debug: true #是否测试
@@ -12,35 +8,32 @@ mta:
     publicKey: MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAuHV05fB6aafE1lMvFtU/eawP0s4uFa2zZThPFGx80l1JZNWaMfQoa8+Gu8reRc/PRnx1N9syTc/zeZYZUfstPn22y8qWPLYwqxyJH53knCj9263M8P6Q4n+MF7pUVUQbkn0FTlyo8eWZlpCOJe9MDTTIhPdIMlrDn31HiFZ8TY0pySh5tEZzhYIaaJjmvQUdQuCWMwdq9uzVtHu++QFmbHCApZbekJcQ1ebaGv76DOiGpPPtlH3mrSGqR/1z0uVwC5iRn5vuax/73a/OPvQGHOVTBq2QBiZHRf23DPO7SMuCpampEVaXIwIW2weCfNnvLCWMQ+v0dxpOVIUx1BlLjwIDAQAB
     privateKey: MIIEvwIBADANBgkqhk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gQCzJ6OlR5k+jJ09kUXIEYnJ+dnvKR1tdhu/p/ha3zTpRfk6l1tMVszaEpiSgRrrOd8SJ7cXRV3/FgsSTD+LD2nHx0mMVqmbCVRZjt1CnuC35BOQgThGZeJbY5aOeR/rgPVH8YBrKK5fE+JhoNq2pivYNSUcSDyGCBACtH0Age2IEQKBgQCQMg1VSfoSUuDL3BaB9O1abfz8RR1EmCIUPUKBKsAYFKcBYc8eFqgzgCnLZVEcx6ceETHYefDeTgethVgxzhno/xflyIJ4Zv3zfvub2ZUbQk5pIIiwrdpIYuEfPyUcGze/gPv8EcMehexwB+sp/a78mGR+6n+kmp9hTlMf2V/enQKBgQDPH5exzUjktHYwlEhEsXOGCUh1gs7KI5d7FcWWubZiWgz3I2F4iVMW9yd1godxr0XUJMuWJqft0c0A/ayPDOCRwxvnxMDEB9qhA4hdfyBdUYKU4sDxn8NmT7/srMbSUyQIzbprA6UPg4Hh68nunvMwf/vX8VK4641y+W3rYYyDjw==
   
-##spring配置
-spring: 
-  ##应用配置 #服务名称
-  application.name: mta-service-file
-  ##监控服务配置
-  boot.admin.client:
-    instance.preferIp: true #使用IP注册
-    url: http://192.168.0.179:1111 #监控服务地址
-  ##数据源配置
-  datasource: 
-    driverClassName: com.mysql.jdbc.Driver
-    url: jdbc:mysql://192.168.0.172:3306/mta_platform?useUnicode=true&characterEncoding=utf8&useSSL=false
-    username: dkuser
-    password: dkuser
-    initialSize: 3        ##初始化连接数, 默认: 10
-    maxActive: 10     ##连接池中保留的最大连接数, 默认: 100
-    minIdle: 3          ##最小空闲连接数量, 默认: initialSize
-    maxIdle: 5         ##最大空闲连接数量, 默认: maxActive
-    testOnBorrow: true    ##访问前验证链接有效性, 默认: false
-    validationQuery: SELECT 1       ##验证数据库连接的有效性sql, 默认: null
-    validationInterval: 30000         ##验证数据库连接频率(毫秒), 默认: 30000
-    removeAbandoned: true           ##是否进行无用链接回收, 默认: false
-    removeAbandonedTimeout: 60    ##链接有效期,超时将被回收(秒), 默认: 60
-    
-#mybatis配置
-mybatis: 
-  configuration: 
-    mapUnderscoreToCamelCase: true ## 开启自动驼峰命名规则映射
-    
+##端口配置
+server.port: 8003 #监听端口
+  
+##数据源配置
+spring.datasource: 
+  driverClassName: com.mysql.jdbc.Driver
+  url: jdbc:mysql://192.168.0.172:3306/mta_platform?useUnicode=true&characterEncoding=utf8&useSSL=false
+  username: dkuser
+  password: dkuser
+  initialSize: 3        ##初始化连接数, 默认: 10
+  maxActive: 10     ##连接池中保留的最大连接数, 默认: 100
+  minIdle: 3          ##最小空闲连接数量, 默认: initialSize
+  maxIdle: 5         ##最大空闲连接数量, 默认: maxActive
+  testOnBorrow: true    ##访问前验证链接有效性, 默认: false
+  validationQuery: SELECT 1       ##验证数据库连接的有效性sql, 默认: null
+  validationInterval: 30000         ##验证数据库连接频率(毫秒), 默认: 30000
+  removeAbandoned: true           ##是否进行无用链接回收, 默认: false
+  removeAbandonedTimeout: 60    ##链接有效期,超时将被回收(秒), 默认: 60
+
+##MYBATIS配置
+mybatis.configuration.mapUnderscoreToCamelCase: true #开启自动驼峰命名规则映射    
+
+
+##服务名称
+spring.application.name: mta-service-file #服务名称
+ 
 ##注册中心配置
 eureka:
   instance: 
@@ -53,11 +46,23 @@ eureka:
     healthcheck.enabled: true #开启健康检测
     serviceUrl.defaultZone: http://192.168.0.179:8761/eureka #配置中心地址
 
-##监控配置    
+
+##监控服务配置
+spring.boot.admin.client: 
+  instance.preferIp: true #使用IP注册
+  url: http://192.168.0.179:1111 #监控服务地址
+  
+##监控端点配置
 management:
   server.port: 18003 #监控端口
   endpoints.web.exposure.include: "*" #开启所有端点
   endpoint.health.show-details: always #显示健康详情
+
+  
+##系统异常配置
+spring.resources.addMappings: false #不为工程中的资源文件建立映射
+spring.mvc.throwExceptionIfNoHandlerFound: true #出现异常时直接抛出,使@RestControllerAdvice可以处理404等异常(需要上面配置false才能生效)
+  
   
 ##日志配置
 logging: