2016-10-30 84 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 { 
... 
}