Spring Boot 全局异常处理@ControllerAdvice
1.使用@ExceptionHandler当前Controller异常处理
package com.chengli.springboot.controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.WebRequest;
@RestController
public class TestController {
@RequestMapping(value = "/")
public String hello() {
throw new RuntimeException();
}
@ExceptionHandler(value = { RuntimeException.class })
public String exception(Exception e, WebRequest webRequest) {
return "出现异常了,在本类处理";
}
}
(2)新建启动入口类,名称:MainConfig,具体代码如下:
package com.chengli.springboot;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class MainConfig {
public static void main(String[] args) {
SpringApplication.run(MainConfig.class, args);
}
}
(3)运行启动,在浏览器输入后,会出现“出异常了,在本类处理”
2.使用@ExceptionHandler全局异常处理
package com.chengli.springboot.exception;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@RestControllerAdvice
public class DefaultExceptionHandlerAdvice {
@ExceptionHandler(value = { Exception.class })
public String exception() {
return "出异常了,全局异常处理";
}
}
(2)这里需要提醒一点的是,优先级问题,同一种异常处理在本类的优先级要高,会优先使用本类的其次是全局的。所以我们这里需要将本类使用@ExceptionHandler的方法先注释掉,然后在浏览器上输入后,出现“出异常了,全局异常处理”。那么就OK啦。
3.使用@InitBinder注解处理绑定值
@InitBinder
public void initBinder(WebDataBinder binder) {
binder.registerCustomEditor(Date.class, new PropertyEditorSupport() {
@Override
public void setAsText(String text) {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
try {
setValue(format.parse(text));
} catch (ParseException e) {
e.printStackTrace();
}
}
});
}
(2)上面的代码我是在处理参数的时候,将日期参数按照指定格式parse后在进行设置。@initBinder注解在很多场景下能用的上,比如你要处理字符串用来编码防止XSS攻击啊或者你要预先做个处理的都可以,这里就不细说了,@initBinder注解是可以放在所有使用了@Controller类中的,也可以放到全局类中,也就是说使用了@ControllerAdvice注解的类。
4400



被折叠的 条评论
为什么被折叠?



