Tag Archives: @RestControllerAdvice

Spring: How to Solve Global exception @restcontrolleradvice

@Restcontrolleradvice is a composite annotation

@ControllerAdvice

@ResponseBody

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

Function: enhance the controller, match the two, and often handle global exceptions

@Controlleradvice works on classes in three ways

Global exception handling: @ModelAttribute

Global data binding: @ModelAttribute

Global data preprocessing: @InitBinder

Global exception handling

@RestControllerAdvice
public class GlobalExceptionDeal {
	@ExceptionHandler(NullPointerException.class)
	@ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
	public ResponseBean dealNullPointerException() {
		ResponseBean responseBean = new ResponseBean(500,"Server exception - null pointer exception");
		return responseBean;
	}
	@ExceptionHandler(Exception.class)
	@ResponseStatus(value=HttpStatus.INTERNAL_SERVER_ERROR)
	public ResponseBean dealUnexpectedException(){
		ResponseBean responseBean=new ResponseBean(505,"Server exception - unknown error");
		return responseBean;
	}
}