一、全局异常捕获
- 1.全局异常捕获注解
- @ExceptionHandler 表示拦截异常
- @ControllerAdvice 是 controller 的一个辅助类,最常用的就是作为全局异常处理的切面类
- @ControllerAdvice 可以指定扫描范围
- @ControllerAdvice 约定了几种可行的返回值
- 如果是直接返回 model 类的话,需要使用 @ResponseBody 进行 json 转换
- 返回 String,表示跳到某个 view
- 返回 modelAndView
- 返回 model + @ResponseBody
- 2.Service代码
- 异常访问:http://localhost:8088/sjyl/insertUser?age=0
@RestController
@Slf4j
public class MemberService {
@RequestMapping("/insertUser")
public int insertUser(int age) {
int j = 1 / age;
return j;
}
}
- 3.全局捕获异常实现
@ControllerAdvice
public class SjylExceptionHandler {
@ExceptionHandler(RuntimeException.class)
@ResponseBody
public Map<Object, Object> exceptionHandler() {
HashMap<Object, Object> result = new HashMap<>();
result.put("code", 500);
result.put("msg", "系统错误");
return result;
}
}
浏览器访问:http://localhost:8088/sjyl/insertUser?age=0
二、SpringBoot项目打包
由于我们的SpringBoot项目已经内置了tomcat容器,所以我们不需要像SpringMVC那样打成war包,我们打成jar包就可以了
打包:使用mvn clean package打包
运行:使用java –jar 包名运行
- 1.进入到项目主目录,删除target目录
- 2.进入cmd命令
- 3.打包命令
mvn clean package
- 4.运行命令
java -jar (上一步生成的jar包路径地址)
D:\test\springboot_helloworld>java -jar D:\test\springboot_helloworld\target\springboot_helloworld-1.0-SNAPSHOT.jar
- 5.运行报错(没有主清单)的解决方案
- 在pom中加上如下配置即可
<mainClass>com.sjyl.App</mainClass>
:需要配置成项目启动类的全限定类名
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
<configuration>
<mainClass>com.sjyl.App</mainClass>
<excludes>
<exclude>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
</exclude>
<exclude>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>