当前位置:网站首页>24: Chapter 3: develop pass service: 7: user defined exceptions (to represent errors in the program); Create graceexceptionhandler to handle exceptions globally and uniformly (build JSON data of corre
24: Chapter 3: develop pass service: 7: user defined exceptions (to represent errors in the program); Create graceexceptionhandler to handle exceptions globally and uniformly (build JSON data of corre
2022-06-30 17:05:00 【Small withered forest】
explain :
【Spring Boot E-commerce projects 17: User module 6 : Registered interface development : Use 【GlobalExceptionHandler】 To handle exceptions globally ;】 User defined exceptions have been introduced , And the strategy of handling custom exceptions globally ; Before reading this blog , Be sure to refer to the above two blogs first ;
● What this blog does , The same as before ;; It's just , On the concrete realization , The mistake lies in the difference of yididididiu ;
stay 【23: The third chapter : Developing a pass service :6: Restrict users 60 Cannot repeat access within 【 Send a text message , Interface 】;】 in , In the interceptor , If it does “ The user is in 60 Repeat access within seconds 【 Send a text message , Interface 】” Of “ Wrong situation ” when , We just printed a sentence ;;; A formal practice , We can throw an exception , To represent this “ Wrong situation ”,
Catalog
1. stay 【imooc-news-dev-common】 In general engineering , establish exception package ;
2. Create custom exception :MyCustomException;( Inheritance is RuntimeException)
One : Formal development ;
1. stay 【imooc-news-dev-common】 In general engineering , establish exception package ;
About exception related classes , We can put it in this bag ;
2. Create custom exception :MyCustomException;( Inheritance is RuntimeException)
package com.imooc.exception; import com.imooc.grace.result.ResponseStatusEnum; /** * Custom exception ; * Purpose : Handle exception information uniformly ; Easy to manage , Easy to decouple ; */ public class MyCustomException extends RuntimeException { // Enumerating class objects private ResponseStatusEnum responseStatusEnum; /** * No arguments structure ; It's not what it takes. ; * It's just , Because we declare a parameterized construct , Its nonparametric construction automatically GG 了 ; * In order to prevent , There may be unnecessary trouble in the future , So I added a nonparametric structure to it ; */ public MyCustomException() { } /** * There are parametric structures : according to 【 incoming , Representing an error message ResponseStatusEnum Enumerating class objects 】, Sure * Instantiate a 【MyCustomException Exception object 】 * @param responseStatusEnum */ public MyCustomException(ResponseStatusEnum responseStatusEnum) { super(" The exception status code is :" + responseStatusEnum.status() + "; The specific information of the exception is :" + responseStatusEnum.msg()); this.responseStatusEnum = responseStatusEnum; } public ResponseStatusEnum getResponseStatusEnum() { return responseStatusEnum; } public void setResponseStatusEnum(ResponseStatusEnum responseStatusEnum) { this.responseStatusEnum = responseStatusEnum; } }explain :
(1) Our custom exception , Inheritance is RuntimeException;; and , We are 【Spring Boot E-commerce projects 16: User module 5 : Registered interface development : Custom exception classes ;】 Custom exception in , Inheritance is Exception;
● adopt 【Java Exception one : Exception definition ; Classification of exceptions 】 You know ,RuntimeException Yes no check abnormal ;;; therefore , When we throw a in the program RuntimeException Abnormal times , We don't need to do it try-catch;;;; thus , We don't know much about code “ Invasive ”;
(2) It is known that , We are in the enumeration class , A lot of error messages are defined ;;;;; When something goes wrong with the program , Sometimes we can use the corresponding error messages , Build a custom MyCustomException Exception object ;
3. Create a tool class :GraceException: According to what was passed in 【ResponseStatusEnum Enumeration class 】, establish ( And throw ) Corresponding customization MyCustomException Exception object ;
package com.imooc.exception; import com.imooc.grace.result.ResponseStatusEnum; /** * Tool class : according to 【 incoming , Representing an error message ResponseStatusEnum Enumerating class objects 】, system * A package 【 Our custom exception MyCustomException abnormal , The object of 】 */ public class GraceException { /** * According to what was passed in 【ResponseStatusEnum Enumeration class , * Create and throw our custom exception MyCustomException object 】 * @param responseStatusEnum */ public static void display(ResponseStatusEnum responseStatusEnum) { throw new MyCustomException(responseStatusEnum); } }explain :
(1) Class content description ;
above , When we throw a custom exception in the program , This custom exception is thrown , Need to be captured by the container ;;; After the container catches this custom exception , We can put the corresponding specific error information , Throw to the front ;
therefore , At this point, we need to do a unified interception ; This is what follows ;
4. establish “ Handle exceptions uniformly handler class ”:GraceExceptionHandler class : To handle exceptions globally , According to 【 Abnormal information 】 Convert to corresponding 【API Unified return object 】;
package com.imooc.exception; import com.imooc.grace.result.GraceJSONResult; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseBody; /** * Unified exception interception and handling ; * Specific information about exceptions can be provided , Build the corresponding GraceJSONResultAPI Unified return object , To the front end ; */ @ControllerAdvice public class GraceExceptionHandler { @ExceptionHandler(MyCustomException.class) @ResponseBody public GraceJSONResult returnMyException(MyCustomException e) { e.printStackTrace(); return GraceJSONResult.exception(e.getResponseStatusEnum()); } }explain :
(1) We are 【Spring Boot E-commerce projects 17: User module 6 : Registered interface development : Use 【GlobalExceptionHandler】 To handle exceptions globally ;】 in , Have done similar work ;;;; The content here , In this blog , There are introductions ;
(2) Take a look 【@ControllerAdvice】 annotation , In fact, you can understand , Here too AOP Principle , To achieve the ;
(3) here , It's based on 【 Abnormal information 】 Convert to corresponding 【API Unified return object 】;;; We are 【14: Chapter two : Architecture back end project :10: encapsulation “ Return results ”;】 in , Created 【API Unified return object 】 namely GraceJSONResult class ;
(4) Self perception ( Understanding may be biased or even wrong ):
● Statement 1: The response is coming soon , That is, when you want to return to the front-end content (PS: This joint is the eye , Is not necessarily Controller Oh , It could also be an interceptor ;; namely , That returns information directly to the front end , Is not necessarily Controller, It may also be interceptors, etc ), It is found that there is another MyCustomException abnormal ;;;;; that , We created here GraceExceptionHandler class , It USES 【 @ExceptionHandler(MyCustomException.class)】 The method of annotation , Will capture , According to 【 Abnormal information 】 Convert to corresponding 【API Unified return object 】 Of JSON Formatted data , Back to the front end ;
● Statement 2: This GraceExceptionHandler class , Real time monitoring 【 The point immediately to return to the front-end content 】( here ,Controller And interceptors , It can be regarded as equivalent );; If , Its have MyCustomException abnormal ;;; that , We created here GraceExceptionHandler class , It USES 【 @ExceptionHandler(MyCustomException.class)】 The method of annotation , Will capture , According to 【 Abnormal information 】 Convert to corresponding 【API Unified return object 】 Of JSON Formatted data , Back to the front end ;
Two : then , stay 【23: The third chapter : Developing a pass service :6: Restrict users 60 Cannot repeat access within 【 Send a text message , Interface 】;】 in , In the interceptor , If it does “ The user is in 60 Repeat access within seconds 【 Send a text message , Interface 】” Of “ Wrong situation ” when , You can throw a corresponding exception ;
3、 ... and : effect ;
(1) First, the whole situation install Look at the whole project ;
(2) then , start-up 【user】 The main startup class of ;
(3) then , On the front page , Two consecutive visits 【 Send SMS interface 】;(PS: Remember to turn on SwitchHosts Virtual domain name )
边栏推荐
- Simpleitk encountered an ITK only supports orthonormal direction cosines error while reading NII
- Several cross end development artifacts
- 异常类_日志框架
- redis淘汰策略
- Mathematical modeling for war preparation 34-bp neural network prediction 2
- 删除有序数组中的重复项 II[双指针--多情况统一]
- AVIC UAV technology innovation board is listed: the fist product with a market value of 38.5 billion is pterodactyl UAV
- [Verilog basics] octal and hexadecimal representation of decimal negative numbers
- 阿里云盘分享压缩包
- 【JVM】类加载相关面试题——类加载过程、双亲委派模型
猜你喜欢

OpenCV中LineTypes各枚举值(LINE_4 、LINE_8 、LINE_AA )的含义

Etcd tutorial - Chapter 9 etcd implementation of distributed locks

redis淘汰策略

Required plug-ins for idea

观测云与 TDengine 达成深度合作,优化企业上云体验
![[JVM] class loading related interview questions - class loading process and parental delegation model](/img/4a/99fee19828b0c1234cc863db88fda1.png)
[JVM] class loading related interview questions - class loading process and parental delegation model

Data mining knowledge points sorting (final review version)

TCP socket and TCP connection

Mathematical modeling for war preparation 33- grey prediction model 2

9:第三章:电商工程分析:4:【通用模块】;(待写……)
随机推荐
IO stream_ recursion
How to connect the Internet Reading Notes - Summary
Delete duplicates in an ordered array ii[double pointers -- unified in multiple cases]
HMS Core音频编辑服务3D音频技术,助力打造沉浸式听觉盛宴
redis数据结构分析
华为帐号多端协同,打造美好互联生活
Internet R & D efficiency practice qunar core field Devops landing practice
Several cross end development artifacts
Compile u-boot source code for stm32p157 development board
Parler du télétravail
Sub chain cross technology source level exploration: an overview of xcvm
Research on helmet wearing detection algorithm
Supplementary
居家办公浅谈远程协助快速提效心得 | 社区征文
The meaning of linetypes enumeration values (line_4, line_8, line_aa) in opencv
坚果云-在新电脑上同步移动硬盘的文件
数据安全合规之后,给风控团队带来了新的问题
数据库系统概论习题册
More dragon lizard self-developed features! Production available Anolis OS 8.6 officially released
IndexSearch











