springboot自定义处理异常

版权声明:本文为博主原创文章,未经博主允许不得转载。你想转载请附加连接哦 https://blog.csdn.net/dmw412724/article/details/89330060

点击返回目录

ssm里处理异常一般是这样处理的:继承自HandlerExceptionResolver然后注册为bean即可。

在springboot里也可以按照上述逻辑写:

public class MyExceptionHandler implements HandlerExceptionResolver {

	@Override
	public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
			Exception ex) {
		ex.printStackTrace();
		return null;
	}

}
@Configuration
public class MvcConfig implements WebMvcConfigurer {
	
	@Override
	public void configureHandlerExceptionResolvers(List<HandlerExceptionResolver> resolvers) {
		resolvers.add(new MyExceptionHandler());
	}
}

当然,在springboot里也可以这样去写,更加简单分明:

@ControllerAdvice
public class MyControllerAdvice{
	
	@ExceptionHandler(BindException.class)
	@ResponseBody
	String handleControllerException(HttpServletRequest request,HttpServletResponse response,HandlerMethod  handler,Throwable ex) {
		System.out.println("异常:"+ex);
		System.out.println(handler.getMethod());
		return ex.getMessage();//
	}
	
	@ExceptionHandler(NullPointerException.class)
	@ResponseBody
	String handleNullPointerException(HttpServletRequest request,HttpServletResponse response,HandlerMethod  handler,Throwable ex) {
		System.out.println("异常:"+ex);
		System.out.println(handler.getMethod());
		return ex.getMessage();//
	}
	
	@ExceptionHandler(Exception.class)
	@ResponseBody
	String handleException(HttpServletRequest request,HttpServletResponse response,HandlerMethod  handler,Throwable ex) {
		System.out.println("异常:"+ex);
		System.out.println(handler.getMethod());
		return ex.getMessage();//
	}

}

不同的异常有不同的处理,非常棒。只是要小心,因为这相当于stwich-case,子类异常要放到父类异常前面吧。

注意以上两种方法如果混用可能会有意想不到的事情:需要详细了解这两种异常处理机制是怎么回事,第一种应该是覆盖默认处理机制,第二种应该是补充默认处理机制。

猜你喜欢

转载自blog.csdn.net/dmw412724/article/details/89330060