Spring

    xiaoxiao2022-07-07  224

    ① 创建一个exception包 ② 在exception包中 创建一个异常(AuthenticationException)继承RuntimeException, 创建UnknowUsernameException与WrongPasswordException异常 继承AuthenticationException异常。

    // 认证异常 public class AuthenticationException extends RuntimeException{ } // 用户名未知异常 public class UnknowUsernameException extends AuthenticationException { } // 密码错误异常 public class WrongPasswordException extends AuthenticationException { }

    ③ 创建一个类用于对全局异常进行统一处理 引用@Component注解, 实现HandlerExceptionResolver接口, 重写HandlerExceptionResolver接口中的 resolveException 方法

    // 全局异常处理 // 只需要让spring创建这个bean就可以直接生效, 配置文件中不需要配置 @Component public class GlobalExceptionResolver implements HandlerExceptionResolver { @Override public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) { return null; } }

    ④ resolveException 方法中:: 统一判断异常具体类型, 根据不同异常返回不同的处理信息

    // 全局异常处理 // 只需要让spring创建这个bean就可以直接生效, 配置文件中不需要配置 @Component public class GlobalExceptionResolver implements HandlerExceptionResolver { @Override public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) { ModelAndView mv = new ModelAndView(); // 统一判断异常具体类型, 根据不同的异常返回不同的信息 if (ex instanceof UnknowUsernameException){ mv.addObject("message","用户名不存在"); mv.setView(new MappingJackson2JsonView()); } else { // 打印异常的堆栈信息 ex.printStackTrace(); mv.addObject("message","服务器开小差了"); mv.setView(new MappingJackson2JsonView()); } return mv; } }

    ⑤ 在service层 (其他层中也可以) 中抛出对应异常

    @Service public class UserServiceImpl implements UserService { @Override public UserBean login(String username, String password) { if ("admin".equals(username)){ if ("admin".equals(password)){ UserBean user = new UserBean(); user.setUsername("admin"); } else { throw new WrongPasswordException(); } } else { // 用户名在数据库中不存在, 抛出 未知用户名异常 throw new UnknowUsernameException(); } return null; } }
    最新回复(0)