aboutsummaryrefslogtreecommitdiff
path: root/lib/errors/errors.go
blob: 13e3b995508f0dafc57077bb589fc5192766c1f6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
// Copyright 2018, Shulhan <ms@kilabit.info>. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// Package errors provide an error type with code.
package errors

import (
	"net/http"
)

//
// E define custom error that wrap underlying error with custom code, message,
// and name.
//
// The Code field is required, used to communicate the HTTP response code.
// The Message field is optional, it's used to communicate the actual error
// message from server, to be readable by human.
// The Name field is optional, intended to be consumed by program, for
// example, to provide a key as translation of Message into user's locale
// defined language.
//
type E struct {
	Code    int    `json:"code,omitempty"`
	Message string `json:"message,omitempty"`
	Name    string `json:"name,omitempty"`
	err     error
}

//
// Internal define an error caused by server.
//
func Internal(err error) *E {
	return &E{
		Code:    http.StatusInternalServerError,
		Message: "internal server error",
		Name:    "ERR_INTERNAL",
		err:     err,
	}
}

//
// InvalidInput generate an error for invalid input.
//
func InvalidInput(field string) *E {
	return &E{
		Code:    http.StatusBadRequest,
		Message: "invalid input: " + field,
		Name:    "ERR_INVALID_INPUT",
	}
}

//
// Error implement the error interface.
//
func (e *E) Error() string {
	return e.Message
}

//
// Unwrap return the internal error only if its not nil; otherwise it will
// return the e itself.
//
func (e *E) Unwrap() error {
	if e.err != nil {
		return e.err
	}
	return e
}