throw error code
Error codes are very important in applications and can improve the maintainability, scalability and reliability of software systems, thereby better supporting error handling and troubleshooting during software development and use.
Luwak designed a mechanism for throwing error codes so that the caller can perform friendly error handling based on different error codes.
ReturnError will interrupt subsequent content, that is, after returnError is executed, the statements following it will not be executed.
Function definition
luwak.returnError (business error status code, business error message)
in
- Business error status code It is a user-defined string used to uniquely identify a certain type of error. Corresponds to the error.data.status value in the returned result
- Business error messages User-defined string, used to briefly describe the error situation, to facilitate users to understand the cause of the error, and corresponds to error.data.message in the returned result.
Naming of business error codes
You can use any string as the error code, Luwak does not enforce this.
The following are some principles for our design errors for reference:
- Uniqueness to avoid using the same error code for different error types
- Readability, being able to clearly express error types and error causes
- One-to-one correspondence with error messages to facilitate developers, operation and maintenance personnel or users to understand error messages and take corresponding measures.
- Should be used in conjunction with logging to allow error tracking and analysis.
Example
Assume that the result is the result returned by the user registration API and false is returned because the user name is occupied. For convenience, the registration interface is not called here but the result is assigned a value directly.
Request message
The JSON-RPC request message is as follows
log.info("print log before returnError");
result = {"success": false, "errorMessage": "the name you used has been occupied"}
if (result.success == false) {
luwak.returnError("USERNAME_OCCUPIED", result.errorMessage)
}
log.info("print log after returnError");
Response message
As shown below, the business error code is in error.data.status and the error information is in error.data.message.
{
"jsonrpc": "2.0",
"error": {
"code": 10000,
"message": "the name you used has been occupied",
"data": "USERNAME_OCCUPIED"
},
"id": "client-unique-request-id"
}
View luwak log
2023/10/26 18:24:22 INFO js_log.go:53 print log before returnError
It can be seen that the log after returnError is not printed, which means that returnError is returned directly, and the statements following it are not executed.
Appendix
For more JSON-RPC 2.0 return result specifications, see JSON-RPC 2.0 Specification