Error Handling
Panduan error handling yang konsisten di seluruh aplikasi.🚨 Error Types
Copy
type AppError struct {
Code string
Message string
StatusCode int
Err error
}
func (e *AppError) Error() string {
return e.Message
}
// Predefined errors
var (
ErrNotFound = &AppError{
Code: "NOT_FOUND",
Message: "Resource not found",
StatusCode: 404,
}
ErrUnauthorized = &AppError{
Code: "UNAUTHORIZED",
Message: "Unauthorized access",
StatusCode: 401,
}
ErrValidation = &AppError{
Code: "VALIDATION_ERROR",
Message: "Validation failed",
StatusCode: 400,
}
)
📝 Error Response
Copy
type ErrorResponse struct {
Error ErrorDetail `json:"error"`
}
type ErrorDetail struct {
Code string `json:"code"`
Message string `json:"message"`
Details []ValidationError `json:"details,omitempty"`
TraceID string `json:"traceId"`
}
func HandleError(c echo.Context, err error) error {
var appErr *AppError
if errors.As(err, &appErr) {
return c.JSON(appErr.StatusCode, ErrorResponse{
Error: ErrorDetail{
Code: appErr.Code,
Message: appErr.Message,
TraceID: getTraceID(c),
},
})
}
// Unknown error
return c.JSON(500, ErrorResponse{
Error: ErrorDetail{
Code: "INTERNAL_ERROR",
Message: "An unexpected error occurred",
TraceID: getTraceID(c),
},
})
}