springMVC uses @ControllerAdvice to implement exception handling

Controller exception handling:

@ResponseStatus(value=HttpStatus.NOT_FOUND)
public class StaffNotFoundException extends Exception {

}


Custom StaffNotFoundException exception class: employee information is not found exception.
The function of @ResponseStatus(value=HttpStatus.NOT_FOUND) is to map the exception to an http 404 exception, that is, the browser receives a 404 error.



@Controller
@RequestMapping("/")
public class PCInfoController {
	
	@Autowired
	PCInfoRestClient PCInfoRestClient;
	
	/**
	 * Personal information page
	 * @param
	 * @return
	 * @throws StaffNotFoundException
	 */
	@RequestMapping(value="info",method=RequestMethod.GET)
	public String staffInfo(Model model) throws StaffNotFoundException {
		
		HashMap staff = PCInfoRestClient.getStaff();
		
		if(staff == null)
			throw new StaffNotFoundException();
		
		
		model.addAttribute("staff", staff);
		return "info";
	}
	
	
	@RequestMapping(value="staff/notfound",method=RequestMethod.GET)
	public String error(Model model)
	{
		return "error";
	}
	
}


In the controller, if the obtained staff is null, a StaffNotFoundException will be thrown.


@ControllerAdvice
public class CommonExceptionHandler {

	@ExceptionHandler(StaffNotFoundException.class)
	public String handleStaffNotFound(Exception exception, WebRequest request)
	{
		return "redirect:/staff/notfound";
	}
}



In the CommonExceptionHandler class annotated with @controllerAdvice, the handleStaffNotFound() method is annotated with @ExceptionHandler(StaffNotFoundException.class), which means that when the controller throws a StaffNotFoundException exception, it will delegate this method to handle it.

One of the most useful scenarios for @controllerAdvice is to collect all @ExceptionHandler methods into one class, so that all exceptions can be handled consistently in one place.

@ControllerAdvice By default, all exceptions thrown by the control will be processed in this class
@ControllerAdvice(annotations = {PCInfoController .class}) configure the controller you need to intercept,
@ControllerAdvice(basePackages = "com.demo") configure the path you need controller under

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326866610&siteId=291194637