如何在Spring Webflux中返回自定义错误主体

问题描述

我对Spring-Webflux有一个问题,尤其是错误代码的返回。我必须设置自定义错误正文和代码。我已经阅读了一些有关自定义错误处理程序的解决方法,但对我来说似乎很肮脏(也许我错了?)。

我的路线的基本含义是登录用户。如果凭据错误或未激活用户,则应返回401,但是如果未使用响应正文{"errorType":"DisabledException"}激活他, 。目前,我正在为Mono的逻辑以及如何返回两个不同的Errors以及如何设置错误主体而苦苦挣扎。
这是我的实际代码:

路线:

@PostMapping("/login/registered")
public Mono<ClientAuthentication> loginRegistered(
        @RequestBody final LoginCredentials loginCredentials) {
    return accountService.getFragJetztCredentialsByEmail(loginCredentials.getLoginId())
            .filter(fragJetztCredentials ->
                    accountService.checkPassword(fragJetztCredentials.getPassword(),loginCredentials.getPassword()) && fragJetztCredentials.getActivationKey() == null
            )
            .switchIfEmpty(Mono.error(new UnauthorizedException("DisabledException")))
            .flatMap(fragJetztCredentials -> accountService.getByEmail(fragJetztCredentials.getEmail()))
            .doOnSuccess(account ->
                    SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(account,null))
            )
            .map(account -> new AccountWithToken(jwtUtil.generateToken(account),account))
            .map(accountWithToken -> {
                final Account user = (Account) accountWithToken.getPrincipal();
                return new ClientAuthentication(user.getId(),accountWithToken.getToken());
            });
}

例外:

@ResponseStatus(code = HttpStatus.UNAUTHORIZED)
public class UnauthorizedException extends RuntimeException {
    private static final long serialVersionUID = 1L;

    public UnauthorizedException() {
        super();
    }

    public UnauthorizedException(final String message) {
        super(message);
    }

    public UnauthorizedException(final Throwable e) {
        super(e);
    }

    public UnauthorizedException(final String message,final Throwable e) {
        super(message,e);
    }
}

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...