Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Springboot uses @ ControllerAdvice annotations to handle system exceptions globally

2025-01-30 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/03 Report--

In our daily development, we often use try catch to handle exceptions. This kind of code is repetitive. We can define exceptions globally through @ controllerAdvice annotation, which greatly reduces the try catch of the code.

Import com.vicrab.api.bean.OperateCode

Import com.vicrab.api.server.model.OperateResult

Import org.apache.shiro.authc.AuthenticationException

Import org.slf4j.Logger

Import org.slf4j.LoggerFactory

Import org.springframework.beans.ConversionNotSupportedException

Import org.springframework.beans.TypeMismatchException

Import org.springframework.http.converter.HttpMessageNotReadableException

Import org.springframework.http.converter.HttpMessageNotWritableException

Import org.springframework.web.HttpMediaTypeNotAcceptableException

Import org.springframework.web.HttpRequestMethodNotSupportedException

Import org.springframework.web.bind.MissingServletRequestParameterException

Import org.springframework.web.bind.annotation.ControllerAdvice

Import org.springframework.web.bind.annotation.ExceptionHandler

Import org.springframework.web.bind.annotation.ResponseBody

Import java.io.IOException

@ ControllerAdvice

Public class ControllerExceptionHandler {

Private static final Logger logger = LoggerFactory.getLogger (ControllerExceptionHandler.class); private static final String logExceptionFormat = "Capture Exception By GlobalExceptionHandler: Code:% s Detail:% s"; / / Runtime exception @ ExceptionHandler (RuntimeException.class) @ ResponseBodypublic OperateResult runtimeExceptionHandler (RuntimeException ex) {return exceptionFormat (OperateCode.EX_RUN, ex);} / / null pointer exception @ ExceptionHandler (NullPointerException.class) @ ResponseBodypublic OperateResult nullPointerExceptionHandler (NullPointerException ex) {return exceptionFormat (OperateCode.EX_NULL, ex) } / / Type conversion exception @ ExceptionHandler (ClassCastException.class) @ ResponseBodypublic OperateResult classCastExceptionHandler (ClassCastException ex) {return exceptionFormat (OperateCode.EX_CAST, ex);} / / IO exception @ ExceptionHandler (IOException.class) @ ResponseBodypublic OperateResult iOExceptionHandler (IOException ex) {return exceptionFormat (OperateCode.EX_IO, ex);} / unknown method exception @ ExceptionHandler (NoSuchMethodException.class) @ ResponseBodypublic OperateResult noSuchMethodExceptionHandler (NoSuchMethodException ex) {return exceptionFormat (OperateCode.EX_NO_SUCH_METHOD, ex) } / / Array out of bounds exception @ ExceptionHandler (IndexOutOfBoundsException.class) @ ResponseBodypublic OperateResult indexOutOfBoundsExceptionHandler (IndexOutOfBoundsException ex) {return exceptionFormat (OperateCode.EX_INDEX_OUT_OF_BOUNDNS, ex);} / / 400Error @ ExceptionHandler ({HttpMessageNotReadableException.class}) @ ResponseBodypublic OperateResult requestNotReadable (HttpMessageNotReadableException ex) {logger.error ("400..requestNotReadable"); return exceptionFormat (OperateCode.BAD_REQUEST, ex) @ ExceptionHandler ({TypeMismatchException.class}) @ ResponseBodypublic OperateResult requestTypeMismatch (TypeMismatchException ex) {logger.error ("400..TypeMismatchException"); return exceptionFormat (OperateCode.BAD_REQUEST, ex);} / / 400Error @ ExceptionHandler ({MissingServletRequestParameterException.class}) @ ResponseBodypublic OperateResult requestMissingServletRequest (MissingServletRequestParameterException ex) {logger.error ("400..MissingServletRequest"); return exceptionFormat (OperateCode.BAD_REQUEST, ex) Error @ ExceptionHandler ({AuthenticationException.class}) @ ResponseBodypublic OperateResult request401 (AuthenticationException ex) {return exceptionFormat (OperateCode.UNAUTHORIZED, ex);} / / 405error @ ExceptionHandler ({HttpRequestMethodNotSupportedException.class}) @ ResponseBodypublic OperateResult request405 (HttpRequestMethodNotSupportedException ex) {return exceptionFormat (OperateCode.METHOD_NOT_ALLOWED, ex);} / / 406error @ ExceptionHandler ({HttpMediaTypeNotAcceptableException.class}) @ ResponseBodypublic OperateResult request406 (HttpMediaTypeNotAcceptableException ex) {logger.error ("406..."); return exceptionFormat (OperateCode.NOT_ACCEPTABLE, ex) Error @ ExceptionHandler ({ConversionNotSupportedException.class, HttpMessageNotWritableException.class}) @ ResponseBodypublic OperateResult server500 (RuntimeException ex) {logger.error ("500..."); return exceptionFormat (OperateCode.INTERNAL_SERVER_ERROR, ex);} / / Stack overflow @ ExceptionHandler ({StackOverflowError.class}) @ ResponseBodypublic OperateResult requestStackOverflow (StackOverflowError ex) {return exceptionFormat (OperateCode.EX_STACK_OVER_FLOW, ex) } / / other errors @ ExceptionHandler ({Exception.class}) @ ResponseBodypublic OperateResult exception (Exception ex) {return exceptionFormat (OperateCode.EX_OTHER, ex);} private OperateResult exceptionFormat (OperateCode operateCode, T ex) {logger.error (String.format (logExceptionFormat, operateCode, ex); return OperateResult.exception (operateCode, ex);}

}

@ ExceptionHandler is used to define the type of exception, which enumerates null pointer exceptions. In fact, you can also implement custom exceptions, such as

Public class MyException extends RuntimeException {

Public MyException (String code, String msg) {this.code = code; this.msg = msg;} private String code;private String msg;// getter & setter

}

Import org.springframework.ui.Model

Import org.springframework.web.bind.WebDataBinder

Import org.springframework.web.bind.annotation.*

Import java.util.HashMap

Import java.util.Map

@ ControllerAdvice

Public class MyControllerAdvice {

/ * * Global exception catch handling * @ param ex * @ return * / @ ResponseBody@ExceptionHandler (value = Exception.class) public Map errorHandler (Exception ex) {Map map = new HashMap (); map.put ("code", 100); map.put ("msg", ex.getMessage ()); return map;} @ ResponseBody@ExceptionHandler (value = MyException.class) public Map myErrorHandler (MyException ex) {Map map = new HashMap () Map.put ("code", ex.getCode ()); map.put ("msg", ex.getMsg ()); return map;}

}

An exception is thrown in controller for testing.

@ RequestMapping ("/ home")

Public String home () throws Exception {

/ / throw new Exception ("Sam error")

Throw new MyException ("101l", "Sam error")

}

Start the application, visit: http://localhost:8080/home

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.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report