当前位置:网站首页>If the program exits abnormally, how to catch the fatal error through the go language?
If the program exits abnormally, how to catch the fatal error through the go language?
2022-06-24 01:25:00 【Tsingsee green rhino video】
Our team often reviews our existing video platforms, such as EasyNVR、EasyGBS Version update and adaptation test of different systems , stay EasyNVR In the beta version , The program exits abnormally , But the corresponding error cannot be found in the log .
We can solve this problem by Go The function of language capturing errors for troubleshooting and sorting . In general , use defer func(){recover() …} Similar functions capture errors in programs , however recover() The function cannot catch the corresponding exception in the following three cases :
1. A new subprocess is running , If... Occurs in the subprocess panic error , It can't be captured ; 2. If directly in the program os.Exit(0), Corresponding defer Functions do not run , The whole program exits directly ; 3. If a fatal error occurs ,recover() Unable to capture , For example, the following code , Can't be captured .
defer func() {
err := recover()
if err != nil {
fmt.Print("err=", err)
}
}()
a := "hello world"
sh := (*reflect.StringHeader)(unsafe.Pointer(&a))
bh := reflect.SliceHeader{
Data: sh.Data,
Len: sh.Len,
Cap: sh.Len,
}
b := *(*[]byte)(unsafe.Pointer(&bh))
b[0] = 'H'A fatal exception will appear directly in the program during operation , Cause the whole program to crash and exit .
But in this case , Unable to write to log , Therefore, the corresponding log can be seen only through the console when the program is running . In this case , The code needs to be processed .
stay Windows In the system , The modified code is as follows :
package elog
import (
"os"
"syscall"
)
var (
kernel32 = syscall.MustLoadDLL("kernel32.dll")
procSetStdHandle = kernel32.MustFindProc("SetStdHandle")
)
func setStdHandle(stdhandle int32, handle syscall.Handle) error {
r0, _, e1 := syscall.Syscall(procSetStdHandle.Addr(), 2, uintptr(stdhandle), uintptr(handle), 0)
if r0 == 0 {
if e1 != 0 {
return error(e1)
}
return syscall.EINVAL
}
return nil
}
// RedirectStderr to the file passed in
func RedirectStderr() (err error) {
logFile, err := os.OpenFile("./test-error.log", os.O_WRONLY|os.O_CREATE|os.O_SYNC|os.O_APPEND, 0644)
if err != nil {
return
}
err = setStdHandle(syscall.STD_ERROR_HANDLE, syscall.Handle(logFile.Fd()))
if err != nil {
return
}
// SetStdHandle does not affect prior references to stderr
os.Stderr = logFile
return
}stay Linux In the system , The modified code is as follows :
package elog
import (
"os"
"syscall"
)
// RedirectStderr to the file passed in
func RedirectStderr() (err error) {
logFile, err := os.OpenFile("./test-error.log", os.O_WRONLY|os.O_CREATE|os.O_SYNC|os.O_APPEND, 0644)
if err != nil {
return
}
err = syscall.Dup3(int(logFile.Fd()), int(os.Stderr.Fd()),0)
if err != nil {
return
}
return
}main Calling code in function
elog.RedirectStderr()
Eventually, if fatal Code , Just write it to test-error.log in , That is, the following documents :
边栏推荐
- "Ai+ education" and "Ai education": one for education and the other for Education
- Thread safety and lock optimization
- S2b2c e-commerce platform in the pharmaceutical and medical industry enables enterprises to grasp differentiated competitive advantages and improve supply chain efficiency
- jdbc
- 4 most common automated test challenges and Countermeasures
- Law / principle / rule / rule / theorem / axiom / essence / Law
- The best Base64 encoding and decoding tutorial in the whole network, with 6 examples!
- Cvpr2022 𞓜 thin domain adaptation
- How to view kubernetes API traffic by grabbing packets
- How to self-study website construction is website construction company reliable
猜你喜欢

Shardingsphere-proxy-5.0.0 implementation of capacity range partition (V)
![2022 postgraduate entrance examination experience sharing [preliminary examination, school selection, re examination, adjustment, school recruitment and social recruitment]](/img/05/e204f526e2f3e90ed9a7ad0361a72e.png)
2022 postgraduate entrance examination experience sharing [preliminary examination, school selection, re examination, adjustment, school recruitment and social recruitment]

GNN上分利器!与其绞尽脑汁炼丹,不如给你的GNN撒点trick吧

【Flutter】如何使用Flutter包和插件

Data management: business data cleaning and implementation scheme

Niu Xuechang's anniversary celebration: software promotion, limited time and free registration code!

Icml'22 | progcl: rethinking difficult sample mining in graph contrast learning

Cvpr2022 𞓜 thin domain adaptation

Installation and use of winscp and putty

An accident caused by a MySQL misoperation, and the "high availability" cannot withstand it!
随机推荐
ICML'22 | ProGCL: 重新思考图对比学习中的难样本挖掘
Dart series: creating a library package
[new secsha!] Have you got the 22 year new seckill activity of Tencent cloud?
Esp8266 OTA remote and wireless upgrade
[technical grass planting] use webhook to automatically deploy my blogs on multiple sites in Tencent cloud
Is it safe to open a stock account online now? Select a state-owned securities firm, and the fastest time to open an account is 8 minutes
Basic templates for various configurations of the SSM framework
Sockfwd a data forwarding gadget
How to open Tencent enterprise mailbox and Tencent enterprise mailbox login portal
Law / principle / rule / rule / theorem / axiom / essence / Law
Disaster recovery series (VI) -- data storage disaster recovery construction
13 `bs_ duixiang. Tag tag ` get a tag object
Real time preview of RTSP video based on webrtc
Selenium crawls stocks in practice
Cross domain and jsonp
How to select storage space for website construction what factors should be considered in selecting space
Remove the cloud disk service display "continued" logo
How to quickly convert stock code into int in quantitative trading?
Golang gets the start timestamp and end timestamp of a past or future week or month
Error reported using worker: uncaught domexception: failed to construct 'worker': script at***