Skip to content

Commit

Permalink
add panic recovery
Browse files Browse the repository at this point in the history
  • Loading branch information
Qaleka committed Dec 15, 2024
1 parent 29fa1be commit 15eb897
Show file tree
Hide file tree
Showing 5 changed files with 76 additions and 4 deletions.
2 changes: 1 addition & 1 deletion cmd/webapp/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ func main() {
mainRouter := router.SetUpRoutes(authHandler, adsHandler, cityHandler, chatsHandler, reviewsHandler)
mainRouter.Use(middleware.RequestIDMiddleware)
mainRouter.Use(middleware.RateLimitMiddleware)
http.Handle("/", middleware.EnableCORS(mainRouter))
http.Handle("/", middleware.RecoverWrap(middleware.EnableCORS(mainRouter)))
if os.Getenv("HTTPS") == "TRUE" {
fmt.Printf("Starting HTTPS server on address %s\n", os.Getenv("BACKEND_URL"))
if err := http.ListenAndServeTLS(os.Getenv("BACKEND_URL"), "ssl/pootnick.crt", "ssl/pootnick.key", nil); err != nil {
Expand Down
63 changes: 63 additions & 0 deletions internal/service/middleware/middleware.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,20 @@ import (
"2024_2_FIGHT-CLUB/internal/service/images"
"2024_2_FIGHT-CLUB/microservices/ads_service/controller/gen"
"context"
"errors"
"fmt"
"github.com/google/uuid"
"golang.org/x/crypto/bcrypt"
"golang.org/x/time/rate"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"gorm.io/driver/postgres"
"gorm.io/gorm"
"log"
"net/http"
"os"
"runtime/debug"
"sync"
"time"
)
Expand Down Expand Up @@ -156,3 +161,61 @@ func ConvertGRPCToRooms(grpc []*gen.AdRooms) []domain.AdRoomsResponse {
}
return Rooms
}

func RecoverWrap(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer func() {
r := recover()
if r != nil {
var err error
switch t := r.(type) {
case string:
err = errors.New(t)
case error:
err = t
default:
err = errors.New("Unknown error")
}
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}()
h.ServeHTTP(w, r)
})
}

func RecoveryInterceptor(
ctx context.Context,
req interface{},
info *grpc.UnaryServerInfo,
handler grpc.UnaryHandler,
) (resp interface{}, err error) {
defer func() {
if r := recover(); r != nil {
fmt.Printf("Panic occurred: %v\n", r)
debug.PrintStack()
err = status.Errorf(codes.Internal, "internal server error: %v", r)
}
}()
return handler(ctx, req)
}

func ChainUnaryInterceptors(interceptors ...grpc.UnaryServerInterceptor) grpc.UnaryServerInterceptor {
return func(
ctx context.Context,
req interface{},
info *grpc.UnaryServerInfo,
handler grpc.UnaryHandler,
) (interface{}, error) {
current := len(interceptors) - 1
var chain grpc.UnaryHandler
chain = func(currentCtx context.Context, currentReq interface{}) (interface{}, error) {
if current < 0 {
return handler(currentCtx, currentReq)
}
interceptor := interceptors[current]
current--
return interceptor(currentCtx, currentReq, info, chain)
}
return chain(ctx, req)
}
}
5 changes: 4 additions & 1 deletion microservices/ads_service/cmd/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,10 @@ func main() {
adsServer := grpcAd.NewGrpcAdHandler(sessionService, adsUseCase, jwtToken)
adsUseCase.StartPriorityResetWorker(ctx)
grpcServer := grpc.NewServer(
grpc.UnaryInterceptor(middleware.UnaryMetricsInterceptor),
grpc.UnaryInterceptor(middleware.ChainUnaryInterceptors(
middleware.RecoveryInterceptor, // интерсептор для обработки паники
middleware.UnaryMetricsInterceptor, // интерсептор для метрик
)),
)
generatedAds.RegisterAdsServer(grpcServer, adsServer)

Expand Down
5 changes: 4 additions & 1 deletion microservices/auth_service/cmd/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,10 @@ func main() {
authServer := grpcAuth.NewGrpcAuthHandler(auUseCase, sessionService, jwtToken)

grpcServer := grpc.NewServer(
grpc.UnaryInterceptor(middleware.UnaryMetricsInterceptor),
grpc.UnaryInterceptor(middleware.ChainUnaryInterceptors(
middleware.RecoveryInterceptor, // интерсептор для обработки паники
middleware.UnaryMetricsInterceptor, // интерсептор для метрик
)),
)
generatedAuth.RegisterAuthServer(grpcServer, authServer)

Expand Down
5 changes: 4 additions & 1 deletion microservices/city_service/cmd/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,10 @@ func main() {
cityServer := grpcCity.NewGrpcCityHandler(citiesUseCase)

grpcServer := grpc.NewServer(
grpc.UnaryInterceptor(middleware.UnaryMetricsInterceptor),
grpc.UnaryInterceptor(middleware.ChainUnaryInterceptors(
middleware.RecoveryInterceptor, // интерсептор для обработки паники
middleware.UnaryMetricsInterceptor, // интерсептор для метрик
)),
)
generatedCity.RegisterCityServiceServer(grpcServer, cityServer)

Expand Down

0 comments on commit 15eb897

Please sign in to comment.