My official account: MarkerHub, Java website: Markerhub.com
For more selected articles, please click: Java Notes Complete.md
Small Hub read:
In fact, the way exceptions are handled is pretty fixed,
- Custom exception
- Global exception handling is usually a combination of @ControllerAdvice+@ExceptionHandler
- The returned message class can add error codes, error messages, and other parameters as required
Did you lose school? Ha ha
- Author: Cs_hnu_scw
- Homepage: blog.csdn.net/Cs_hnu_scw
Scene into
Me: oink, oink, oink…
Xiao Bai: get up, get up, get up, get up…
I: small white, again encounter what matter, so be in a hurry to burn off of, young person, do things want steady
Small white: I met a very serious problem, want to let you guide guide me!
M: Oh, this time so humbly ask, that I am not angry, you say, how?
Small white: is that I am in the process of development, because it is a team development, so, sometimes logic is right, then somehow appear some problems, and shows the effect is very embarrassed, but also is not easy to found the problem, every time to see the background to know the problem, but after deployment to the server, can only look at the Log Log to locate the problem.
Me: Right, this project development is a team thing, this is very normal, what’s the fuss?
Xiaobai: So, I think, is there any way to friendly display of anomalies (unknown and known) in the system? In this way, we are relatively more convenient in communication ah, otherwise, always looking at a bunch of messy mistakes, quite upset. Me: I think I understand what you mean. You just want to be able to display the exceptions in the system in a friendly way or to facilitate the development of your team.
Small white: rightness rightness, be such a meaning.
I: this certainly had, and you now encounter of this problem, in fact in each system all should have carry on processing, although it is more simple, but not allow to be overlooked, also have a lot of important thing of ~ that listen to a lesson well!
Small white: really happy ,,,,, can’t wait
The import
The problem
For Web projects, as we all know, development is usually done by a team, not a single person, and the development team also has people on the front and back end, so having certain specifications is essential.
One problem we’ve probably all encountered is that there is a big difference between the development environment and the one that goes live. The development environment is for us developers, while the formal environment is a system that looks at us from the user’s point of view. Think about a problem. If we run into an exception that we didn’t run into during development, and the user finds out about it, the user experience will be very bad, and this is a big no-no for us.
In that case, we also know that during the development process, there are so many exceptions may occur, so it contains we have considered, but there are some hidden exception is we may neglect, so, in order to be able to will potentially abnormal not found by the user directly, and affect the user experience, this — — — — — — — — — exception handling, , is indispensable!
Unified exception handling
Definition: simply put, it is for our system in the exception, give a certain standard processing results. (For example, the default is to print the exception stack directly to the page, which is extremely ugly.)
Emerging scene
Custom exceptions predicted by the developer
In development, the developer can anticipate certain possible situations, which is a state of active processing.
System exceptions that developers cannot predict
When there are exceptions in development that the developer cannot fully think about, this is a potentially possible exception state.
The interaction between the front and back ends is abnormal
Because of the separation of the front and back ends and the different development directions of the front and back ends, exceptions can occur.
The development environment
-
Windows 7 + lousy laptop
-
IDEA + SpringBoot + Mybatis +Mysql
Development steps
Create a custom exception
Analysis: In the system, there are system exceptions and our man-made custom exceptions, so in order to effectively handle different exceptions, it is very necessary to have our custom exception class.
package com.hnu.csapp.exception; /** * @author: SCW * @date: Created in PM 3:18 2018/11/29 0029 * @description: Custom exceptions, in order to distinguish between system exceptions and easier system specific handling * @modified By: * @version: 1 */ public class MyException extends RuntimeException{private Integer code; public Integer getCode() { return code; } public void setCode(Integer code) { this.code = code; } public MyException(String message) { super(message); } /** * constructor load, * @param code * @param message */ public MyException(Integer code,String message) {super(message); this.code = code; }}Copy the code
Create the wrapper entity that the message returns to
Analysis: back to the front to the background data, we often are the returned JSON format of the data (of course, not confined to this one), then JSON is a form of formatting, so, we should be effective for this form to give a certain return specification, so also convenient front-end for us to return the data interpretation.
For example: many cases are generally the following format:
"Data ": {// return data content} "retMes": success // return information} "data": {// return data content}Copy the code
So, we can define the following class:
package com.hnu.csapp.exception; /** * @author: SCW * @date: Created in PM 3:09 2018/11/29 0029 * @description: * @modified By: * @version: 1 */ public class Result<T> {private Integer code; // Return message private String MSG; // Return data private T data; public Integer getCode() { return code; } public void setCode(Integer code) { this.code = code; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public T getData() { return data; } public void setData(T data) { this.data = data; }}Copy the code
Defines a series of enumerations to return information
Analysis: In the system, we should have some uniform code corresponding to certain content, so that developers can facilitate timely processing.
package com.hnu.csapp.exception; /** * @author: SCW * @date: Created in PM 3:23 2018/11/29 0029 * @description: * @modified By: * @version: 1 */ public enum ResultEnum {/** * ResultEnum is successful. */ SUCCESS(200," SUCCESS "), /** * system exception. ErrorCode: -1 */ SystemException(-1," SystemException "), /** * unknown exception. ErrorCode: 01 */ UnknownException(01," UnknownException "), /** * service exception. ErrorCode: 02 */ ServiceException(02, "ServiceException "), /** * service error. ErrorCode: 03 */ MyException(03," business error "), /** * Error level. ErrorCode: 04 */ InfoException(04, "warning level error "), /** * Database operation exception. ErrorCode: 05 */ DBException(05," database operation exception "), /** * parameter validation error. ErrorCode: 06 */ ParamException(06," Parameter verification error "); private Integer code; private String msg; ResultEnum(Integer code, String msg) { this.code = code; this.msg = msg; } public Integer getCode() { return code; } public String getMsg() { return msg; }}Copy the code
Define the message return utility class
Analysis: For message return, this is a very common work, so we can encapsulate it with a utility class, can carry out effective code encapsulation, reduce redundant code.
package com.hnu.csapp.exception; /** * @author: SCW * @date: Created in PM 3:12 2018/11/29 0029 * @description: A utility class that returns message processing, mainly for handling successes and failures of operations. 1 */ public class ResultUtil {/** * public static Result getSuccess(object) * @param object * @return */ object){ Result result = new Result(); // Set the return code result.setcode (200); // Set the message result.setmsg (" success "); result.setData(object); return result; } @return */ public static Result getSuccess(){return getSuccess(null); } @param MSG error message @param o error data * @return */ public static Result getError(Integer code, String MSG, Object o){Result Result = new Result(); result.setCode(code); result.setMsg(msg); result.setData(o); return result; } /** * reload, * @param code * @param MSG * @return */ public static Result getError(Integer code, String msg){ return getError(code, msg, null); }}Copy the code
Define the exception unified handling class (emphasis)
Analysis: This is the key to how to achieve unified exception handling, and I have also annotated the different handling cases separately, so you can take a careful look at the code, I’m sure you will understand.
package com.hnu.csapp.exception; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; /** * @author: SCW * @date: Created in PM 3:20 2018/11/29 0029 * @description: * @modified By: * @version: 1 */ @controllerAdvice public class ExceptionHandle {// Add exception log printing private Final static Logger Logger = LoggerFactory.getLogger(ExceptionHandle.class); Public static final String DEFAULT_ERROR_VIEW = "error"; /** * Return content in json format * @param e * @return */ @ExceptionHandler(exception.class) @responseBody public Object handle(HttpServletRequest req, If (e instanceof MyException){MyException MyException = (MyException)e; return ResultUtil.getError(myException.getCode(),myException.getMessage()); }else{logger.error(" [system exception] ={}",e); return ResultUtil.getError(ResultEnum.SystemException.getCode(),ResultEnum.SystemException.getMsg()); }} public Boolean isAjax(HttpServletRequest Request){return;} public Boolean isAjax(HttpServletRequest Request){return (request.getHeader("X-Requested-With") ! = null && "XMLHttpRequest".equals(request.getHeader("X-Requested-With").toString())); } /* / note: // It is better to use json format in the development process. @ExceptionHandler(value = exception.class) public ModelAndView DefaulTTerrorHandler (HttpServletRequest req, Exception e) throws Exception { e.printStackTrace(); If (isAjax(req)){// If (e instanceof MyException){MyException myException = (MyException)e; return ResultUtil.getError(myException.getCode(),myException.getMessage()); }else{logger.error(" [system exception] ={}",e); return ResultUtil.getError(ResultEnum.SystemException.getCode(),ResultEnum.SystemException.getMsg()); ModelAndView mav = new ModelAndView(); ModelAndView mav = new ModelAndView(); Mav. addObject("exception", e); // This is the content to be returned to the page. mav.addObject("url", req.getRequestURL()); mav.setViewName(DEFAULT_ERROR_VIEW); return mav; * /}}}Copy the code
Define the exception handling page
Analysis: this case, it is mainly in formal environment, because we are in the test environment, will generally or error in JSON format displayed on the page, or stack and when online, then you must have a uniform error page, so you can’t let users find what problem is the system appeared.
In this case, I have put the specific “error” page in another post of mine, which you are welcome to read.
Blog.csdn.net/Cshnuscw/ar…
The effect
1: Development environment
2: Formal environment
Analysis: When an exception occurs, the following page is displayed. (This page is a reference to a blog friend, feel very interesting, old driver ~)
conclusion
Exception handling, perhaps we seem very simple, however, it contains other thoughts is a kind of general situation thought, this is our developers in the development process should pay attention to point, we not only need to pay attention to each one of us development point of the task, but in a global perspective to look at the whole project, it also can improve we open the height of the problem.
Unified exception handling is something that exists in every project, but it may be implemented in different ways or displayed differently, which is not the point.
Exception unification is not too difficult, but it can help us extend to other relevant development aspects, such as:
-
Login to intercept
-
Rights management
-
Log management
-
Transaction processing
-
Data control and filtering
-
.
So, we should learn to see from one problem to another similar problems, so that our system will be more robust, efficient and scalable.
Recommended reading
Java Notes Complete.md
Great, this Java site, everything! https://markerhub.com
The UP master of this B station, speaks Java really good!