gpt4 book ai didi

spring - 如何通过 ControllerAdvice 在 ExceptionHandling 中设置优先级

转载 作者:行者123 更新时间:2023-12-05 03:10:22 25 4
gpt4 key购买 nike

我正在实现 2 ControllersAdvice。处理异常CommonAdvice 和 UserAdvice

常见建议

@ControllerAdvice(annotations = RestController.class)
public class CommonAdvice {

@ExceptionHandler(Exception.class)
public ResponseEntity<ExceptionBean> handleException(Exception e) {
ExceptionBean exception = new ExceptionBean(Causes.ANOTHER_CAUSE);
return new ResponseEntity<ExceptionBean>(exception, HttpStatus.INTERNAL_SERVER_ERROR);
}

}

用户建议

@ControllerAdvice(assignableTypes = { requestUserMapper.class })
public class UserAdvice {

@ExceptionHandler(NotUniqueUserLoginException.class)
public ResponseEntity<ExceptionBean> handleAlreadyFound(NotUniqueUserLoginException e) {
System.out.println("this is me : " + Causes.USER_ALREADY_EXIST.toString());
ExceptionBean exception = new ExceptionBean(Causes.USER_ALREADY_EXIST);
return new ResponseEntity<ExceptionBean>(exception, HttpStatus.INTERNAL_SERVER_ERROR);
}

现在,当我抛出 NotUniqueUserException 时,这是一个处理和异常的 CommonAdvice。

我测试过,UserAdvice 工作正常。有办法在这个类上设置优先级吗?

@Edit - 添加控件映射

@RequestMapping(value = "add", method = RequestMethod.POST)
public ResponseEntity<GT_User> addUser(@RequestBody GT_User newUser) throws NotUniqueUserLoginException, Exception {

if (this.userService.exist(newUser.getLogin())) {
throw new NotUniqueUserLoginException(Causes.USER_ALREADY_EXIST.toString());
} else {
GT_User addesUser = this.userService.addUser(newUser);
return new ResponseEntity<GT_User>(addesUser, HttpStatus.OK);
}
}

最佳答案

在添加时为 ControllerAdvice 设置更高的优先级:

import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import com.genealogytree.webapplication.dispatchers.requestUserMapper;

@ControllerAdvice(assignableTypes = { requestUserMapper.class })
@Order(Ordered.HIGHEST_PRECEDENCE)
public class UserAdvice {
...
}

在添加时将较低的优先级设置为 ControolerAdvice

import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import com.genealogytree.webapplication.dispatchers.requestUserMapper;

@ControllerAdvice(assignableTypes = { requestUserMapper.class })
@Order(Ordered.LOWEST_PRECEDENCE)
public class CommonAdvice {
...
}

关于spring - 如何通过 ControllerAdvice 在 ExceptionHandling 中设置优先级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40334360/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com