我实现了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);
}
}
UserAdvice
@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 - 添加Controllel Mapping
@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);
}
}
答案 0 :(得分:2)
在添加时为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 {
...
}
在添加
时将较低优先级设置为ControolerAdviceimport 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 {
...
}