Skip to content

How to remove the redirect response header from ExceptionHandler? #159

@KonngExplorer

Description

@KonngExplorer
@Controller
@RequestMapping("/htmx/admin/user/")
public class HxAuthController {
    @HxRequest
    @RequestMapping("doLogin")
    @HxRedirect("/admin/document/article/article-table")
    public String doLogin(@RequestBody LoginRequest request) {
        String password = request.getPassword();
        String username = request.getUsername();

        if (StrUtil.isBlank(email) && StrUtil.isBlank(username)) {
            throw new LoginException(USERNAME_INCORRECT, "Account or password error",);
        }

        if (StrUtil.isBlank(password)) {
            throw new LoginException(PASSWORD_INCORRECT, "Account or password error");
        }

        boolean success = authService.login(username , password);

        if (!success) {
            throw new LoginException(INTERNAL_ERR, "login failed", false);
        }

        return "none";
    }
}
@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    @ExceptionHandler({LoginException.class})
    @ResponseBody
    public Object handleException(LoginException e, HttpServletRequest request, HttpServletResponse response) {
        ModelAndView modelAndView = new ModelAndView();

        if (request.getHeader(HtmxRequestHeader.HX_REQUEST.getValue()) != null) {
            modelAndView.addObject("msg", e.getMessage());
            response.addHeader(HtmxResponseHeader.HX_RESWAP.getValue(), HxSwapType.BEFORE_END.getValue());
            response.addHeader(HtmxResponseHeader.HX_RESELECT.getValue(), "#alert-warning");
            response.addHeader(HtmxResponseHeader.HX_RETARGET.getValue(), "body");
            modelAndView.setViewName("admin/component/alert-warning");
            return modelAndView;
        }
        return RestResult.failure(e.getMessage());
    }
}

According to the above code, I set the redirect url for successful login using HxRedirect annotation in Controller, I handle the login exception in Handler method of exception handling class, when the exception occurs I want to prompt instead of redirect, after testing whether I set HtmxResponseHeader.HX_REDIRECT in Handler exception handling method or not, it will redirect to "/htmx/admin/user/", is there something wrong with me?

Metadata

Metadata

Assignees

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions