栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Springboot全局异常处理

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Springboot全局异常处理

pom.xml

spring-boot-devtools的范围设置为provided,打包的时候不会打包这个jar包,防止异常时泄露信息,具体见参考连接。



	4.0.0
	
		org.springframework.boot
		spring-boot-starter-parent
		2.6.2
		 
	
	com.example
	demo
	0.0.1-SNAPSHOT
	demo
	Demo project for Spring Boot
	
		1.8
	
	
		
			org.springframework.boot
			spring-boot-starter-web
		

		
			org.springframework.boot
			spring-boot-devtools
			provided
			true
		
		
			org.projectlombok
			lombok
			true
		
		
			org.springframework.boot
			spring-boot-starter-test
			test
		
	

	
		
			
				org.springframework.boot
				spring-boot-maven-plugin
				
					
						
							org.projectlombok
							lombok
						
					
				
			
		
	



配置文件

server.servlet.context-path的值为/api时,如果访问的地址不是以api开头将不会进入到异常捕捉。所以最好是为/

server.servlet.context-path=/api
spring.jackson.default-property-inclusion=non_null
spring.mvc.throw-exception-if-no-handler-found=true
spring.web.resources.add-mappings=false
全局异常处理
@Slf4j
@ResponseBody
@ControllerAdvice
public class GlobalExceptionHandler {

	@ExceptionHandler(value = Exception.class)
	public Result exceptionHandler(HttpServletRequest httpServletRequest, Exception e) {
		log.error("内部错误", e);
		return new Result(500, "Internal Server Error", null);
	}

}
结果实体
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Result {

	private int code;
	private String message;
	private Object data;

}
Controller
@RestController
@RequestMapping("test")
public class TestController {

	@RequestMapping
	public @ResponseBody Result test() {
		return new Result(200, "OK", null);
	}

}

参考连接:https://blog.csdn.net/w1014074794/article/details/106038996/

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/677870.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号