当前位置:网站首页>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 :
边栏推荐
- How to quickly convert stock code into int in quantitative trading?
- How to view kubernetes API traffic by grabbing packets
- Kubernetes' ci/cd practice based on Jenkins spinnaker - adding product image scanning
- Error reported using worker: uncaught domexception: failed to construct 'worker': script at***
- What is the website domain name trademark registration process? What is the use of a website domain name trademark?
- Dart series: metaworld pubspec Yaml file details
- Thread safety and lock optimization
- Selenium crawls stocks in practice
- [ICPR 2021] tiny object detection in aerial images
- Coordinate system "slang" in GIS world
猜你喜欢

js输入输出语句,变量
Shengdun technology joined dragon lizard community to build a new open source ecosystem

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

Theoretical analysis of countermeasure training: adaptive step size fast countermeasure training

LSF opens job idle information to view the CPU time/elapse time usage of the job

Perhaps the greatest romance of programmers is to commemorate their dead mother with a software

13 `bs_duixiang.tag标签`得到一个tag对象

Installation and use of winscp and putty

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

LMS Virtual. Derivation method of lab acoustic simulation results
随机推荐
985 Android programmers won the oral offer of Alibaba P6 in 40 days. After the successful interview, they sorted out these interview ideas
[planting grass by technology] 13 years' record of the prince of wool collecting on the cloud moving to Tencent cloud
Cvpr2022 𞓜 thin domain adaptation
Dart series: metaworld pubspec Yaml file details
Data management: business data cleaning and implementation scheme
[technical grass planting] take you to Tencent cloud's private cloud disk in ten minutes
对抗训练理论分析:自适应步长快速对抗训练
Application configuration management, basic principle analysis
Code practice | ground extraction with logo-loam
jdbc
js输入输出语句,变量
Implementation of automatic triggering of inward delivery order after outward delivery order PGI in SAP inter company sto process
Is the domain name available for trademark registration? How long is the trademark registration cycle?
LMS Virtual. Derivation method of lab acoustic simulation results
. Net core cross platform development bbs forum (connotation source code + complete operation video)
Installation and use of winscp and putty
Basic DDoS commands
How to improve program performance
"Ai+ education" and "Ai education": one for education and the other for Education
Leetcode lecture on algorithm interview for large factories 2 Time space complexity