In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly introduces springboot how to achieve global exception handling and custom exception classes, the article is very detailed, has a certain reference value, interested friends must read it!
Global exception handling and custom exception class global exception handling
Define a processing class, annotated with @ ControllerAdvice.
@ ControllerAdvice Note: controller Enhancement, a component registered by @ Component.
Work with @ ExceptionHandler to enhance all @ requestMapping methods.
For example: @ ExceptionHandler (Exception.class) is used to capture all thrown exception in the method of @ requestMapping.
Code:
@ ControllerAdvicepublic class GlobalDefultExceptionHandler {/ / declare the exception to be caught @ ExceptionHandler (Exception.class) @ ResponseBody public String defultExcepitonHandler (HttpServletRequest request,Exception e) {return "error";}}
In this way, the global exception handling class is complete. You can add your own logic.
Then there is another problem, sometimes when we need business logic to throw a custom exception, we need to customize the business exception class.
Define class:BusinessException so that it inherits from RuntimeException.
Description: because some businesses need to be rolled back. However, the transaction of spring only performs a rollback operation on RuntimeException. So if you need to roll back, you have to inherit RuntimeException.
Public class BusinessException extends RuntimeException {}
Then, now let's refine this class a little bit.
When we throw a business exception, we generally need an error code and an error message. It helps us to locate the problem.
So it is as follows:
Public class BusinessException extends RuntimeException {/ / Custom error code private Integer code; / / Custom constructor, leaving only one so that it must enter the error code and content public BusinessException (int code,String msg) {super (msg); this.code = code;} public Integer getCode () {return code;} public void setCode (Integer code) {this.code = code;}}
At this time, we found that there is another problem, if written in this way, it is difficult to manage the matching between these business exceptions and error codes after there is more code. So optimize it again.
Assemble the error codes and error messages for unified management.
Define an enumeration of a business exception public enum ResultEnum {UNKONW_ERROR (- 1, "unknown error"), SUCCESS (0, "success"), ERROR (1, "failure"),; 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;}}
At this point, the business exception class:
Public class BusinessException extends RuntimeException {private static final long serialVersionUID = 1L; private Integer code; / / error code public BusinessException () {} public BusinessException (ResultEnum resultEnum) {super (resultEnum.getMsg ()); this.code = resultEnum.getCode ();} public Integer getCode () {return code;} public void setCode (Integer code) {this.code = code;}}
Then modify the global exception handling class:
@ ControllerAdvicepublic class GlobalDefultExceptionHandler {/ / declare the exception to be caught @ ExceptionHandler (Exception.class) @ ResponseBody public Result defultExcepitonHandler (HttpServletRequest request,Exception e) {e.printStackTrace (); if (e instanceof BusinessException) {Log.error (this.getClass (), "business exception:" + e.getMessage ()); BusinessException businessException = (BusinessException) e Return ResultUtil.error (businessException.getCode (), businessException.getMessage ());} / / unknown error return ResultUtil.error (- 1, "system exception:\ n" + e);}}
Determine whether this is a business exception. And system exceptions can be handled separately.
Global exception handling configures springboot Restful to use
@ ControllerAdvice, @ ExceptionHandler, @ ResponseBody implement global exception handling
The @ ControllerAdvice annotation defines a global exception handling class
@ ExceptionHandler specifies the type of exception intercepted by a custom error handling method
If the same exception is covered by a small range of exception classes and a large range of exception handlers at the same time, a small range of exception handlers will be selected.
1. Define exception business class
/ * * exception VO * * @ date February 17, 2017 * @ since 1.0.0 * / public class ExceptionVO {private String errorCode; private String message; public String getMessage () {return message;} public void setMessage (String message) {this.message = message;} public String getErrorCode () {return errorCode;} public void setErrorCode (String errorCode) {this.errorCode = errorCode }}
two。 Define custom exceptions
Package exception;/** * numerous data Exception * * @ date 17-4-25 * @ since 1.0.0 * / public class NotFoundException extends SystemException {public NotFoundException (String message) {super (message);}} / * system exception * * @ date February 12, 2017 * @ since 1.0.0 * / public class SystemException extends RuntimeException {private static final long serialVersionUID = 1095242212086237834L; protected Object errorCode; protected Object [] args Public SystemException () {super ();} public SystemException (String message, Throwable cause) {super (message, cause);} public SystemException (String message) {super (message);} public SystemException (String message, Object [] args, Throwable cause) {super (message, cause); this.args = args } public SystemException (String message, Object [] args) {super (message); this.args = args;} public SystemException (Object errorCode, String message, Throwable cause) {super (message, cause); this.errorCode = errorCode;} public SystemException (Object errorCode, String message) {super (message); this.errorCode = errorCode } public SystemException (Object errorCode, String message, Object [] args, Throwable cause) {super (message, cause); this.args = args; this.errorCode = errorCode;} public SystemException (Object errorCode, String message, Object [] args) {super (message); this.args = args; this.errorCode = errorCode;} public SystemException (Throwable cause) {super (cause) } public Object [] getArgs () {return args;} public Object getErrorCode () {return errorCode;}}
3. Define a global exception handling class
Import java.util.HashMap;import java.util.Map;import java.util.stream.Collectors;import NotFoundException;import org.apache.commons.collections.CollectionUtils;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.context.MessageSource;import org.springframework.context.NoSuchMessageException;import org.springframework.context.i18n.LocaleContextHolder;import org.springframework.http.HttpStatus;import org.springframework.validation.BindException;import org.springframework.validation.FieldError 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.bind.annotation.ResponseStatus;import ExceptionVO;/** * WEB exception handler * * @ date February 16,2017 * @ since 1.0.0 * / @ ControllerAdvice ("web") / / specify the interception range of exception handling period public class WebExceptionHandler {static Logger LOG = LoggerFactory.getLogger (WebExceptionHandler.class) @ Autowired private MessageSource messageSource; @ ExceptionHandler (FieldException.class) @ ResponseStatus (HttpStatus.CONFLICT) / / specify http response status @ ResponseBody / * * No data found * * @ param e * @ return * / @ ExceptionHandler (NotFoundException.class) / / specify exception type @ ResponseStatus (HttpStatus.NOT_FOUND) @ ResponseBody public ExceptionVO handleNotFoundException (NotFoundException e) {ExceptionVO vo = new ExceptionVO () FillExceptionVO (e, vo); return vo;} @ ExceptionHandler (SystemException.class) @ ResponseStatus (HttpStatus.CONFLICT) @ ResponseBody public ExceptionVO handleSystemException (SystemException e) {ExceptionVO vo = new ExceptionVO (); fillExceptionVO (e, vo); return vo } @ ResponseStatus (HttpStatus.INTERNAL_SERVER_ERROR) @ ExceptionHandler (Exception.class) public void globalError (Exception e) {LOG.error (e.getMessage (), e) } / * populate the exception response message * * @ param e * @ param vo * / private void fillExceptionVO (SystemException e, ExceptionVO vo) {if (e.getMessage ()! = null) {String message = e.getMessage (); try {message = messageSource.getMessage (e.getMessage (), e.getArgs (), LocaleContextHolder.getLocale ()) } catch (NoSuchMessageException ex) {; / ignore} vo.setMessage (message);} vo.setErrorCode (String.valueOf (e.getErrorCode ();}} springboot returns ModelAndViewpackage exception.handler;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.springframework.web.servlet.HandlerExceptionResolver;import org.springframework.web.servlet.ModelAndView @ Commpentpublic class OverallExceptionHandler implements HandlerExceptionResolver {@ Override public ModelAndView resolveException (HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception ex) {ModelAndView mav = new ModelAndView (); System.out.println (ex.getMessage ()); mav.addObject ("errMsg", ex.getMessage ()); mav.setViewName ("error"); return mav;}}
Other ways:
@ ControllerAdvicepublic class GlobalExceptionHandler {@ ExceptionHandler (value = Exception.class) public ModelAndView resolveException (HttpServletRequest request, Exception ex) throws Exception {ModelAndView mav = new ModelAndView (); System.out.println (ex.getMessage ()); mav.addObject ("errMsg", ex.getMessage ()); mav.setViewName ("error"); return mav }} these are all the contents of the article "how springboot implements global exception handling and custom exception classes". Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.