Spring MVC使用@ExceptionHandler注解异常处理(18)

    技术2023-10-30  99

    Spring MVC使用@ExceptionHandler注解异常处理

    控制层异常处理接口exceptionBaseHandler控制层exceptionController 创建 exceptionBaseHandler类,并在该类中使用 @ExceptionHandler 注解声明异常处理方法

    控制层异常处理接口exceptionBaseHandler

    package control; import org.springframework.web.bind.annotation.ExceptionHandler; import javax.servlet.http.HttpServletRequest; import java.sql.SQLException; public class exceptionBaseHandler { @ExceptionHandler public String exception(HttpServletRequest httpServletRequest,Exception ex){ httpServletRequest.setAttribute("ex", ex); // 根据不同错误转向不同页面,即异常与view的对应关系 if (ex instanceof SQLException) { return "sql-error"; }else { return "error"; } } }

    控制层exceptionController

    package control; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import java.sql.SQLException; @Controller @RequestMapping("/exception") public class exceptionController extends exceptionBaseHandler { @RequestMapping("/login") public String login() throws Exception{ throw new SQLException("data base error"); } }
    Processed: 0.012, SQL: 9