当前位置:网站首页>@Controlleradvice + @exceptionhandler handles controller layer exceptions globally
@Controlleradvice + @exceptionhandler handles controller layer exceptions globally
2022-06-28 14:18:00 【Java collection】
Preface
For database related Spring project , We usually put Business Configure in Service layer , When a database operation fails, let Service Layer throws a runtime exception , Control layer try catch Handle ,Spring The transaction manager will roll back .
In this way , our Controller The layer has to be try-catch Service Layer of abnormal , Otherwise, some unfriendly error messages will be returned to the client . however ,Controller Each method body of the layer writes some templated try-catch Code for , It's ugly and hard to maintain , In particular, it is necessary to Service When different exceptions of layer are handled differently .
Global exception handling ( collocation @ExceptionHandler)
seeing the name of a thing one thinks of its function ,@ControllerAdvice Namely @Controller Enhanced Edition [email protected] It is mainly used to process global data , General collocation @ExceptionHandler Use . Here are the introduction .
0、 Advantages and disadvantages
advantage : take Controller Layer exceptions and data verification exceptions are handled in a unified way , Reduce template code , Reduce the amount of coding , Improve scalability and maintainability .
shortcoming : Can only handle Controller Layer not captured ( Throw out ) It's abnormal , about Interceptor( Interceptor ) Layer of abnormal ,Spring Exceptions in the framework layer , There's nothing we can do .
1、 Basic usage
1)@ControllerAdvice The most common usage scenario is global exception handling . Suppose there is a file upload function in our project , And the file upload size limit is configured .
2) If the user uploads a file that exceeds the size limit , Will throw an exception , At this time, you can use the @ControllerAdvice combination @ExceptionHandler Define the global exception capture mechanism , The specific code is as follows :
Code instructions :
GlobalExceptionHandler Class added @ControllerAdvice annotation . When the system starts , This class will be scanned to Spring In the container .
handleException Method with @ExceptionHandler annotation , It defines Exception.class( It could be something else Exception Subclasses of and Exception Inherited custom class of , Such as NullPointerException.class) Indicates that the method is used to process Exception(NullPointerException) Exception of type . If you want this method to handle all types of exceptions , Only need to NullPointerException Change to Exception that will do .
The parameters of the exception handling method can have exception instances 、HttpServletResponse as well as HttpServletRequest、Model etc. . The return value of the exception handling method can be a segment JSON、 One ModelAndView、 A logical view name, etc .
Use the above annotation to configure a class
/**
* Created by kinginblue on 2017/4/10.
* @ControllerAdvice + @ExceptionHandler Achieve the overall situation Controller Layer exception handling
*/
@ControllerAdvice
public class GlobalExceptionHandler {
private static final Logger LOGGER = LoggerFactory.getLogger(GlobalExceptionHandler.class);
/**
* Handle all unknowable exceptions
* @param e
* @return
*/
@ExceptionHandler(Exception.class)
@ResponseBody
AppResponse handleException(Exception e){
LOGGER.error(e.getMessage(), e);
AppResponse response = new AppResponse();
response.setFail(" operation failed , Official account Java selected !");
return response;
}
/**
* Handle all business exceptions
* @param e
* @return
*/
@ExceptionHandler(BusinessException.class)
@ResponseBody
AppResponse handleBusinessException(BusinessException e){
LOGGER.error(e.getMessage(), e);
AppResponse response = new AppResponse();
response.setFail(e.getMessage());
return response;
}
}The above exception information indicates known business exceptions and unknown captured exceptions ,BusinessException It is an exception class defined by itself
public class BusinessException extends RuntimeException {
public BusinessException(String message){
super(message);
}
}Write a tool class , Transfer this exception message to , Throw it out
public static void isTrue(boolean expression, String error){
if(!expression) {
throw new BusinessException(error);
}
}This method is used below , Will write some exceptions you know , Judge , Throw the exception for processing .
This can be spring Self contained return body ResponseEntity, Declare and define the specific return object information , Such as this
@ExceptionHandler(JyspException.class)
public ResponseEntity<ExceptionResult> handleException(JyspException e) {
return ResponseEntity.status(e.getExceptionEnum().getCode())
.body(new ExceptionResult(e.getExceptionEnum()));
}Custom exceptions
@Getter
@AllArgsConstructor
@NoArgsConstructor
public class JyspException extends RuntimeException{
private ExceptionEnum exceptionEnum;
}Enumerate your exception information classes
@Getter
@NoArgsConstructor
@AllArgsConstructor
public enum ExceptionEnum {
/**
* Wrong user name or password
*/
INVALID_USERNAME_PASSWORD(400, " Wrong user name or password !"),
/**
* Failed to save user name
*/
SAVE_USER_ERROR(400, " Failed to save user name !"),
/**
* Role saving failed
*/
CREAT_ROLE_ERROR(500," Role saving failed ");
private int code;
private String msg;
}The above example uses enumeration to manage several known exceptions
among @ExceptionHandler(Exception.class) Exception returned , You can also customize exceptions , My uses enumerations to handle , It can also be handled in code , How the abnormal information comes from , It is the exception you encounter when writing code , you throws Way to throw out , Then use your own exception information , Throw it into the control layer , Handle through the global exception handling class , Friendly throw to the front , For example, an exception is thrown through code processing
@Service
public class DogService {
@Transactional
public Dog update(Dog dog){
// some database options
// Simulated dog's new name conflicts with other dog's name
BSUtil.isTrue(false, " Dog names have been used ...");
// update database dog info
return dog;
}
}This anomaly is something you can expect , But there are some anomalies you can't predict , Or missing , Then the following method will be used to friendly prompt the front end
@ExceptionHandler(Exception.class)
ResponseEntity<ExceptionResult> handleException(Exception e) {
log.error(e.getMessage(), e);
ExceptionResult response = new ExceptionResult();
response.setStatus(500);
response.setMsg(" operation failed !");
return ResponseEntity.ok(response);
}Code instructions
Logger Log all exceptions .
@ExceptionHandler(BusinessException.class) That's right BusinessException Handling of business exceptions , And get the error prompt in the business exception , Return to the client after construction .
@ExceptionHandler(Exception.class) That's right Exception Exception handling , Play the role of revealing the bottom , No matter Controller There is something unexpected in the code executed by the layer , All return unified error prompts to the client .
remarks : above GlobalExceptionHandler Just go back to Json To the client , Greater play space needs to be done according to the needs .
Reference resources :https://blog.csdn.net/asd051377305/article/details/104773800
Copyright notice : This article is an original blog article , follow CC 4.0 BY-SA Copyright agreement , For reprint, please attach the original source link and this statement .
https://blog.csdn.net/qq_41134142/article/details/110400896
official account “Java selected ” The published content indicates the source of , All rights reserved ( Those whose copyright cannot be verified or whose source is not indicated all come from the Internet , Reprinted , The purpose of reprinting is to convey more information , The copyright belongs to the original author . If there is any infringement , Please contact the , The author will delete the first time !
Many people have asked recently , Is there any readers Communication group ! The way to join is simple , official account Java selected , reply “ Add group ”, You can join the group !
Java Interview questions ( Wechat applet ):3000+ The road test questions , contain Java Basics 、 Concurrent 、JVM、 Threads 、MQ series 、Redis、Spring series 、Elasticsearch、Docker、K8s、Flink、Spark、 Architecture design, etc , Brush questions online at any time !
------ Special recommendation ------
Special recommendation : Focus on the most cutting-edge information and technology sharing , Official account for preparing for overtaking on curves and various open source projects and efficient software ,「 Big coffee notes 」, Focus on finding good things , It's worth your attention . Click the official account card below to follow .
If the article helps , Click to see , Forward! !
边栏推荐
- 2022 recurrent training question bank and online simulation examination for safety inspection of metal and nonmetal mines (underground mines)
- 锐捷交换机配置ssh password登录命令[通俗易懂]
- @ControllerAdvice + @ExceptionHandler 全局处理 Controller 层异常
- Idea global search shortcut settings
- Multi dimensional monitoring: the data base of intelligent monitoring
- Kubernetes' in-depth understanding of kubernetes (II) declaring organizational objects
- Based on asp Net based document retrieval system
- CVPR disputes again: IBM's Chinese draft papers were accused of copying idea, who won the second place in the competition
- How to handle the safest account opening with Huatai Securities app
- What is the progress of China open source with 7.55 million developers?
猜你喜欢

2022下半年软考考试时间安排已确定!

Rslo: self supervised lidar odometer (real time + high precision, icra2022)

中国内地仅四家突围 联想智慧颐和园荣获 “2022年IDC亚太区智慧城市大奖”

PC Museum - familiar and strange ignorant age

Based on asp Net based document retrieval system

欧拉恒等式:数学史上的真正完美公式!

iNFTnews | 科技巨头加快进军Web3和元宇宙

推荐四款可视化工具,解决 99% 的可视化大屏项目!

基于 Nebula Graph 构建百亿关系知识图谱实践

Dry goods | how to calculate the KPI of scientific researchers, and what are the h index and G index
随机推荐
30 sets of JSP website source code collection "suggestions collection"
flutter 系列之:flutter 中的 offstage
2022 Chinese cook (Advanced) test questions and online simulation test
2022金属非金属矿山安全检查(地下矿山)复训题库及在线模拟考试
Regular matching numbers, English and English symbols
[binary tree] the minimum string starting from the leaf node
黑苹果安装教程OC引导「建议收藏」
仅用递归函数和栈操作逆序一个栈
Multi dimensional monitoring: the data base of intelligent monitoring
Inftnews | technology giants accelerate their march into Web3 and metauniverse
Reading notes of Mr. toad going to see a psychologist
Summary of 2021 computer level III database
木兰开放作品许可证1.0面向社会公开征求意见
PC Museum - familiar and strange ignorant age
SPI interface introduction -piyu dhaker
Mulan open work license 1.0 open to the public for comments
Deveco studio 3.0 editor configuration tips
Configuration file encryption (simple use of jasypt)
Arcgis 矢量中心点生成矩形并裁剪tif图像进行深度学习样本训练
【二叉树】在二叉树中分配硬币