How to use exceptions correctly in microservice architecture
This article will introduce to you the correct use of exceptions in microservice architecture. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.
The correct use of exceptions ranks among the top three in importance in the microservice architecture. No comments.
The correct use of exceptions It ranks among the top three in importance in the microservice architecture. No comments.
Curdboys, long time no see. I wish you all a happy Dragon Boat Festival. I want to talk about exceptions recently. My thinking seems to have formed a closed loop. I hope this combination can be helpful to your business code.
The following will only discuss the best languages in the world and the most ecologically complete languages. I don’t have any opinions.
Similarities and Differences of Exceptions
PHP The design of exceptions in PHP7 is consistent with Java's Exception extends Throwable, but there are still some subtle differences in historical reasons and design concepts. . For example, exceptions in PHP have code attributes, so there are multiple exceptions clustered into the same exception, and then different business logic codes are written according to code in the catch block.
But Java exceptions have no code and cannot be designed like this. Different exceptions can only be used for different situations. Therefore, we are accustomed to encapsulating services through packaging classes when exposed to the outside world, instead of directly relying on the transparent transmission of exceptions.
Uniform exception handling
In Java code, the most criticized thing is the numerous try catches. I don’t have any objections. Just grab a piece of code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
|
Many times I just write a try catch without thinking, regardless of whether there are non-runtime exceptions in it. A better way is to use aop to intercept all service method calls, uniformly take over exceptions and handle them.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
|
There is a small problem. If the exception information of service A is returned directly to caller B, there may be some potential risks. The caller can never be trusted, even if he is a third-generation poor peasant. . Because it is not certain how the caller will handle the error message, it may be returned directly to the front end as json.
RuntimeException
Exceptions in Java can be divided into runtime exceptions and non-runtime exceptions. Runtime exceptions do not need to be caught, nor do they need to be caught in methods. Mark throw Exception. For example, if we use the Preconditions tool class in the guava package in the method, the IllegalArgumentException thrown is also a runtime exception.
1 2 3 4 5 6 7 8 |
|
We can also use this feature to customize our own business exception class to inherit RuntimeException
1 |
|
For situations that do not comply with business logic, XXServiceRuntimeException will be thrown directly
1 2 3 4 5 6 7 8 9 10 11 |
|
and then in aop performs unified processing and makes corresponding optimizations. For the previous rough approach, exceptions other than XXServiceRuntimeException and IllegalArgumentException should be recorded internally and no longer exposed to the outside world. However, you must remember to string together distributed links through requestId. In DataResult Return in to facilitate troubleshooting.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
|
Abnormal monitoring
As for the closed loop, after using the custom exception class, the threshold for monitoring and alarming the abnormal log can be reduced a lot, and the alarm To be more precise, take the monitoring of Alibaba Cloud SLS as an example
1 |
|
What is monitored here is the log recording exception log ①
Exception in PHP
The problems mentioned above in Java also exist in PHP. If you don't use 3 methods to simulate aop, you can't reflect that PHP is the best language in the world.
1 2 3 4 5 6 7 8 9 |
|
Similar to the above architectural logic, we will not repeat the pseudo code. , basically consistent. It is also possible to customize your own business exception class to inherit RuntimeException, and then perform external output processing.
However, there is some historical baggage in PHP. When originally designed, many runtime exceptions were output as Notice and Warning errors, but the error output lacked a call stack, which was not conducive to troubleshooting
1 2 3 4 5 6 7 8 9 |
|
1 |
|
You can't see the specific parameters, nor can you see the call stack. If you use set_error_handler ErrorException, it will be very clear.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
|
The last printed information is
1 2 3 4 5 6 7 8 |
|
Modify the above function
1 2 3 |
|
and it will not be captured, because the PHP Fatal error: Uncaught TypeError is thrown, PHP7 With the new
class Error implements Throwable, there will be Stack in the PHP system error log, but it cannot be connected in series with the entire business system. Here we have to talk about the design of the log. We expect to use a traceId like Java. All logs are concatenated, from Nginx logs to normal info level logs in PHP and these Uncaught TypeErrors, so the default output is taken over to the system error log and recorded to a unified place in the catch code block. Then simply modify it here to
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
|
catch Throwable to accept Error and Exception.
But set_error_handler cannot handle some errors, such as E_PARSE errors. You can use register_shutdown_function to cover up.
值得注意的是register_shutdown_function的用意是在脚本正常退出或显示调用exit时,执行注册的函数。
是脚本运行(run-time not parse-time)出错退出时,才能使用。如果在调用register_shutdown_function的同一文件的里面有语法错误,是无法注册的,但是我们项目一般都是分多个文件的,这样就其他文件里有语法错误,也能捕获了
1 2 3 4 5 6 |
|
如果你想直接使用这些代码(PHP的)直接到项目可能会有很多坑,因为我们习惯了系统中有很多 notice 了,可以将 notice 的错误转成异常之后主动记录,但是不对外抛出异常即可。
推荐学习:php视频教程
The above is the detailed content of How to use exceptions correctly in microservice architecture. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics





JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

In PHP8, match expressions are a new control structure that returns different results based on the value of the expression. 1) It is similar to a switch statement, but returns a value instead of an execution statement block. 2) The match expression is strictly compared (===), which improves security. 3) It avoids possible break omissions in switch statements and enhances the simplicity and readability of the code.

In PHP, you can effectively prevent CSRF attacks by using unpredictable tokens. Specific methods include: 1. Generate and embed CSRF tokens in the form; 2. Verify the validity of the token when processing the request.
