【问题标题】:Override not-found exception handler in micronaut在 micronaut 中覆盖未找到的异常处理程序
【发布时间】:2021-09-12 22:44:32
【问题描述】:

我正在尝试覆盖 micronaut 中的 not-found 异常处理程序。

我想抛出自定义错误格式,但找不到要替换的异常处理程序。

我目前的实现:

@Produces
@Singleton
@Requires(classes = {Exception.class, ExceptionHandler.class})
//@Replaces(NotFoundExceptionHandler.class)
public class MyNotFoundExceptionHandler implements ExceptionHandler<Exception, HttpResponse<?>> {
    
    @Override
    public HttpResponse<?> handle(HttpRequest request, Exception exception) {
        return HttpResponse.notFound();
    }

}

默认的 micronaut 异常处理程序会在 not-found 上抛出这种格式:

{
    "message": "Page Not Found",
    "_links": {
        "self": {
            "href": "/api/not-found",
            "templated": false
        }
    }
}

我已经覆盖了其他默认异常处理程序,例如 ConstraintExceptionHandlerUnsatisfiedRouteHandler,但是对于 not-found,记录器不会在控制台中打印异常:

20:43:23.863 [default-nioEventLoopGroup-1-5] DEBUG i.m.h.s.netty.RoutingInBoundHandler - Request GET /api/not-found
20:43:23.864 [default-nioEventLoopGroup-1-5] DEBUG i.m.h.s.netty.RoutingInBoundHandler - No matching route: GET /api/not-found
20:43:23.864 [default-nioEventLoopGroup-1-5] DEBUG i.m.web.router.RouteMatchUtils - Route match attribute for request (/api/not-found) not found

有人知道要覆盖哪个异常处理程序吗?

【问题讨论】:

    标签: java netty micronaut


    【解决方案1】:

    你可以在这里找到你要找的东西https://guides.micronaut.io/latest/micronaut-error-handling-maven-java.html#global-error

    在任何控制器中使用此代码应该没问题:

    @Error(status = HttpStatus.NOT_FOUND, global = true)
    fun notFoundHandler(request: HttpRequest<*>): HttpResponse<JsonError> {
        return HttpResponse.status<JsonError>(HttpStatus.NOT_FOUND).body(JsonError("Page '$request' Not Found"))
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-01-23
      • 1970-01-01
      • 2021-06-07
      • 2021-09-17
      • 1970-01-01
      • 2020-06-28
      • 2016-06-04
      相关资源
      最近更新 更多