2016-10-30 48 views
1

我实现了2个ControllersAdvice。处理异常 CommonAdvice和UserAdvice如何通过ControllerAdvice在ExceptionHandling中设置优先级

常见咨询

@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映射

@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

能你提供了实际的控制器代码和异常堆栈跟踪? – developer

+0

在这里,你是。但正如我已经告诉的那样。 hadleException()被评论,handleAlreadyFound()工作正常。当我添加handleAlreadyfound()int在同一个类,在handleException之前)它也可以。所以,这只是piority的一个问题......我认为...... – VANILKA

+0

好吧......对不起......我找到了解决办法。问题是..我的英语...我被优先搜索。而不是ORDER ...简单的注释@Order解决了我的问题。 – VANILKA

回答

1

要在添加高优先级设置为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 { 
... 
}