其他分享
首页 > 其他分享> > Spring-全局异常处理-@RestControllerAdvice

Spring-全局异常处理-@RestControllerAdvice

作者:互联网

@RestControllerAdvice是复合注解
@ControllerAdvice
@ResponseBody

import org.springframework.web.bind.annotation.RestControllerAdvice;

作用:对Controller进行增强,两者搭配,常做全局异常处理

@ControllerAdvice 作用在类上,有三种用法

  1. 全局异常处理
@RestControllerAdvice
public class GlobalExceptionDeal {
	@ExceptionHandler(NullPointerException.class)
	@ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
	public ResponseBean dealNullPointerException() {
		ResponseBean responseBean = new ResponseBean(500,"服务器异常--空指针异常");
		return responseBean;
	}
	@ExceptionHandler(Exception.class)
	@ResponseStatus(value=HttpStatus.INTERNAL_SERVER_ERROR)
	public ResponseBean dealUnexpectedException(){
		ResponseBean responseBean=new ResponseBean(505,"服务器异常--未知错误");
		return responseBean;
	}
}

标签:responseBean,Spring,ResponseBean,public,RestControllerAdvice,异常,全局
来源: https://www.cnblogs.com/a999/p/15466603.html