Line data Source code
1 : // Package apperr は、アプリケーション全体で共通的に扱う
2 : // エラーコードと HTTP ステータスマッピングを提供します。
3 : package apperr
4 :
5 : import "net/http"
6 :
7 : // Code represents a stable, application-wide error code.
8 : // It should be used for client-facing error classification and logging.
9 : type Code string
10 :
11 : const (
12 : // CodeBadRequest indicates malformed inputs: JSON decode errors,
13 : // missing required keys at transport-level, or type mismatches.
14 : CodeBadRequest Code = "BAD_REQUEST"
15 :
16 : // CodeUnprocessable indicates validation failures: structurally valid
17 : // inputs that fail business/field validation rules.
18 : CodeUnprocessable Code = "UNPROCESSABLE"
19 :
20 : // CodeNotFound indicates that a requested single resource does not exist.
21 : CodeNotFound Code = "NOT_FOUND"
22 :
23 : // CodeConflict indicates a write conflict such as unique constraint violations.
24 : CodeConflict Code = "CONFLICT"
25 :
26 : // CodeUnauthorized indicates authentication is required and has failed or not provided.
27 : CodeUnauthorized Code = "UNAUTHORIZED"
28 :
29 : // CodeForbidden indicates the authenticated principal lacks permission.
30 : CodeForbidden Code = "FORBIDDEN"
31 :
32 : // CodeInternal indicates an unexpected server-side error.
33 : CodeInternal Code = "INTERNAL"
34 : )
35 :
36 : // HTTPStatusOf returns a conventional HTTP status code for a given application Code.
37 3 : func HTTPStatusOf(code Code) int {
38 3 : switch code {
39 0 : case CodeBadRequest:
40 0 : return http.StatusBadRequest // 400
41 0 : case CodeUnprocessable:
42 0 : return http.StatusUnprocessableEntity // 422
43 3 : case CodeUnauthorized:
44 3 : return http.StatusUnauthorized // 401
45 0 : case CodeForbidden:
46 0 : return http.StatusForbidden // 403
47 0 : case CodeNotFound:
48 0 : return http.StatusNotFound // 404
49 0 : case CodeConflict:
50 0 : return http.StatusConflict // 409
51 0 : default:
52 0 : return http.StatusInternalServerError // 500
53 : }
54 : }
|