spring boot: GlobalDefaultExceptionHandler方法内的友好错误提示,全局异常捕获
当你的某个控制器内的某个方法报错,基本上回显示出java错误代码,非常不友好,这个时候可以通过新建GlobalDefaultExceptionHandler.java文件,
1.加上@ControllerAdvice注解,
2. 然后复写defaultExceptionHandler方法,在方法上添加@ResponseBody输出注解,
以及@ExceptionHandler(Exception.class)注解,就能友好的已文字的信息显示错误信息l
package com.muyang.boot22.config;
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
@ControllerAdvice
public class GlobalDefaultExceptionHandler {
@ExceptionHandler(Exception.class)
@ResponseBody
public String defaultExceptionHandler(HttpServletRequest req,Exception e){
//是返回的String.
//ModelAndView -- 介绍 模板引擎...?
// ModelAndView mv = new ModelAndView();
// mv.setViewName(viewName);
return "对不起,服务器繁忙,请稍后再试!";
}
}
参考项目:
pom.xml参考代码
org.springframework.boot
spring-boot-starter-parent
1.5.9.RELEASE
UTF-8
1.8
org.springframework.boot
spring-boot-starter-web
javax.servlet
jstl
org.springframework.boot
spring-boot-starter-tomcat
provided
org.apache.tomcat.embed
tomcat-embed-jasper
provided
junit
junit
3.8.1
test
com.alibaba
fastjson
1.2.15
org.springframework.boot
spring-boot-devtools
true
true
org.springframework.boot
spring-boot-maven-plugin
true
App.java参考代码
package com.muyang.boot22;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.web.HttpMessageConverters;
import org.springframework.context.annotation.Bean;
import org.springframework.http.converter.HttpMessageConverter;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
/**
* Hello world!
*
*/
@SpringBootApplication
public class App
{
//fastJson配置
@Bean
public HttpMessageConverters fastJsonHttpMessageConverters()
{
FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
FastJsonConfig fastJsonConfig = new FastJsonConfig();
fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat);
fastConverter.setFastJsonConfig(fastJsonConfig);
HttpMessageConverter> converter = fastConverter;
return new HttpMessageConverters(converter);
}
public static void main( String[] args )
{
//System.out.println( "Hello World!" );
SpringApplication.run(App.class, args);
}
}
HelloController.java样例
package com.muyang.boot22.controller;
import java.util.Map;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class HelloController
{
@RequestMapping("/hello")
public void index(Mapmap)
{
//map.put("name", "张三");
//return "hello";
int i = 1024/0;
}
}
运行App.java
访问 http://localhost:8080/hello时,报错。能友好提示