How to deal with exceptions in the project, and write code to catch exceptions in every place where exceptions may occur? This is obviously unreasonable, and it is also unmaintainable when the project gets bigger and bigger. So how do we ensure that our code for handling exceptions is streamlined and easy to maintain? This is what this article is about -> exception handling.
We can use the @ExceptionHandler annotation to achieve zero-configuration exception capture and processing.
First, create a parent class BaseController for the controller in the package com.ray.controllers of our project, as follows:
/** * @author Ray * @date 2018/4/21 0021 */ public abstract class BaseController { @ExceptionHandler public String exception(HttpServletRequest request, Exception e){ //Add your own exception handling logic, such as logging request.setAttribute("exceptionMessage", e.getMessage()); / / Different processing according to different exception types if(e instanceof SQLException){ return "sqlerror"; }else{ return "error"; } } }
Second, modify the IndexController in the project so that it inherits from BaseController for testing:
package com.ray.controllers; import com.ray.auth.AuthPassport; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; import java.sql.SQLException; /** * @author Ray * @date 2018/4/21 0021 */ @Controller public class IndexController extends BaseController{ @RequestMapping(value = "/hello") public ModelAndView index() throws SQLException { //test throw new SQLException("Database exception.."); } }
Finally, add the sqlerror.jsp view to the views folder to display error messages:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %> <% String path = request.getContextPath(); String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>Insert title here</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> </head> <body> ${exceptionMessage} </body> </html>
Run the project:
You can see that the exception has been caught and displayed, so as long as all our other Controllers are inherited from BaseController, the centralized capture and processing of exceptions can be realized.