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 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog