自定义异常的处理

Exisi 2022-06-28 14:33:43
Categories: Tags:

示例

public class CustomException extends RuntimeException{

    public CustomException(){

        super();

    }

    

    public CustomException(String message){

        super(message);

    }

}

 

 

@Controller

public class UserController {

 

    @RequestMapping("login")

    public ModelAndView login(String userName, String age) throw CustomException{

        ModelAndView mav = new ModelAndView();

        mav.setViewName("welcome"); 

if(!userName.equals("zhangsan")){

throw new CustomException("用户名已存在"); //抛出自定义的异常

}

        return mav;

    }

}

 

@ControllerAdvice
public class MyGlobalExceptionHandler {

 

@ExceptionHandler(CustomException.class)

public ModelAndView handlerCustomException(Exception e){

        System.out.println(e);

ModelAndView mav = new ModelAndView();

nav.setViewName("nameError");

nav.addObject("tips", "请更换用户名");

        return nav;

}