Paw*_*ski 4 java exception spring-mvc graphql graphql-java
我正在构建使用 GraphQL 和Leangen graphql-spqr 的Web 应用程序。
我有异常处理问题。例如,在服务类中,我使用 spring bean 验证来检查某些有效性,如果不正确,则抛出 ConstraintViolationException。
有没有办法添加一些异常处理程序来向客户端发送正确的消息?类似于ExceptionHandler用于 rest api 中的控制器?或者也许应该以其他方式完成?
我发现的解决方案是实现 DataFetcherExceptionHandler,覆盖 onException 方法并将其设置为默认异常处理程序。
public class ExceptionHandler implements DataFetcherExceptionHandler {
@Override
public DataFetcherExceptionHandlerResult onException(DataFetcherExceptionHandlerParameters handlerParameters) {
Throwable exception = handlerParameters.getException();
// do something with exception
GraphQLError error = GraphqlErrorBuilder
.newError()
.message(exception.getMessage())
.build();
return DataFetcherExceptionHandlerResult
.newResult()
.error(error)
.build();
}
}
Run Code Online (Sandbox Code Playgroud)
并将其设置为查询和突变的默认异常处理程序
GraphQL.newGraphQL(someSchema)
.queryExecutionStrategy(new AsyncExecutionStrategy(new ExceptionHandler()))
.mutationExecutionStrategy(new AsyncExecutionStrategy(new ExceptionHandler()))
.build();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2523 次 |
| 最近记录: |