Skip to content

Commit

Permalink
errors
Browse files Browse the repository at this point in the history
  • Loading branch information
iesreza committed May 27, 2024
1 parent 23db9f6 commit f089dd0
Show file tree
Hide file tree
Showing 3 changed files with 87 additions and 66 deletions.
66 changes: 0 additions & 66 deletions errors/context.go

This file was deleted.

23 changes: 23 additions & 0 deletions evo.context.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package evo

import (
"fmt"
"github.com/getevo/evo/v2/lib/errors"
"net/url"
"reflect"
"strings"
Expand Down Expand Up @@ -135,7 +136,29 @@ func (r *Request) WriteResponse(resp ...any) {
r._writeResponse(r.Response)
return
}
if v, ok := instance.(errors.HTTPError); ok {
if v.StatusCode > 0 {
r.Status(v.StatusCode)
}
if len(v.Cookies) > 0 {
for idx := range v.Cookies {
r.SetRawCookie(v.Cookies[idx])
}
}
if v.ContentType != "" {
r.SetHeader("Content-Type", v.ContentType)
} else {
r.SetHeader("Content-Type", fiber.MIMEApplicationJSONCharsetUTF8)
}

if len(v.Headers) > 0 {
for header, value := range v.Headers {
r.SetHeader(header, value)
}
}
r.Write(v.Data)
return
}
if v, ok := instance.(outcome.Response); ok {

if v.StatusCode > 0 {
Expand Down
64 changes: 64 additions & 0 deletions lib/errors/errors.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
package errors

import (
"fmt"
"github.com/getevo/evo/v2/lib/outcome"
"github.com/getevo/evo/v2/lib/text"
)

type HTTPError outcome.Response

var (
NotFound = New("Not Found", 404)
BadRequest = New("Bad Request", 400)
Unauthorized = New("Unauthorized", 401)
Forbidden = New("Forbidden", 403)
Internal = New("Internal Server Error", 500)
NotAcceptable = New("Not Acceptable", 406)
Conflict = New("Conflict", 409)
Precondition = New("Precondition Failed", 412)
UnsupportedMedia = New("Unsupported Media Type", 415)
Gone = New("Gone", 410)
RequestTimeout = New("Request Timeout", 408)
RequestEntityTooLarge = New("Request Entity Too Large", 413)
RequestURITooLong = New("Request URI Too Long", 414)
RequestHeaderFieldsTooLarge = New("Request Header Fields Too Large", 431)
UnavailableForLegalReasons = New("Unavailable For Legal Reasons", 451)
PayloadTooLarge = New("Payload Too Large", 413)
TooManyRequests = New("Too Many Requests", 429)
)

func New(err ...interface{}) HTTPError {
var r = Response{
Success: false,
Error: "Internal Server Error",
}
var out = HTTPError{
StatusCode: 500,
}

for i, _ := range err {
switch v := err[i].(type) {
case string:
r.Error = v
case error:
r.Error = v.Error()
case int:
out.StatusCode = v
default:
r.Error = fmt.Sprint(v)
}
}
out.Data = text.ToJSON(r)
return out
}

func (e HTTPError) Code(code int) HTTPError {
e.StatusCode = code
return e
}

type Response struct {
Success bool `json:"success"`
Error string `json:"error,omitempty"`
}

0 comments on commit f089dd0

Please sign in to comment.