doumu1951 2015-12-17 12:10
浏览 52

在应用程序的每个模块中对错误(恒定错误)进行分组的好方法

I have an Go app (web service) which returns errors in json like this:

{errorString: "internal server error"}

It's not ok because "internal server error" is just some programmer error string not usefull for client. The solution is to add error codes:

{errCode: 1, errorString: "internal server error"}

Now, client known that 1 means "internal server error" and can process it as want. For example, show for user message "Internal Server Error" or (in my case) the same in russian lang.

Ok.

So, obviously i need some file where all error constants will be described. For ex. errors.go

const (
   ErrNo = iota

   // Common Errors
   ErrNotFound
   ErrInternalServerError

   **// More specified errors**
)

The problem is in More specified errors section.

I have 2 ways:

  1. places all errors definiton in one file errors.go
  2. try to place specific errors to each related file:

my controller is devided on several files in package server:

clienthandler.go -- for client requests, orderhandler.go -- for orders requests and so on.

specific client errors must be places in clienthandler.go, order errors in orderhandler.go

But how it can be realized?

I know one simple solution: Take some max count of errors for each controller, for example 1000.

clienthandler.go

package server

const (
   ErrCheckIdCity = 1000*1 + iota
   ErrCheckName
)

that is 1000 errors (from 1000 to 1999) reserved for this file

orderhandler.go

package server

const (
   ErrCheckIdCity = 1000*2 + iota
   ErrCheckItem
)

that is 1000 errors (from 2000 to 2999) reserved for this file

But disadvantge is that we limit myself by 1000 errors per controller

May be thers is some better way? Or i need just use one global errros.go file ) ?

  • 写回答

1条回答 默认 最新

  • douling8772 2015-12-17 12:38
    关注

    Place each error where it's originated and export it.

    See the link from my comment.

    var ErrInvalidParam = fmt.Errorf(“invalid parameter [%s]”, param)
    

    If you want to add an error code, create a new type satisfying the error interface and add the appropriate members like errorCode or related data.

    If you want, create a build method as helper, similar as errors.New does

    评论

报告相同问题?

悬赏问题

  • ¥15 我的数据无法存进链表里
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端