2017-02-13 36 views
-2

這是我的ExceptionHandler類在HTTP異常返回自定義消息

@ResponseStatus(HttpStatus.NOT_FOUND) 
public class NotFoundException extends Exception { 

    private static final long serialVersionUID = -1964839652066902559L; 

    public NotFoundException(String message) { 
     super(message); 
    } 
} 

在我的服務,我有

@Service 
public class myService { 
public String getName() throws NotFoundException{ 
      logger.error("Name not found"); 
      throw new NotFoundException("Name not found"); 
     } 
} 

我得到的迴應是:

{ 
    "timestamp": 1486967853916, 
    "status": 404, 
    "error": "Not Found", 
    "exception": "com.exceptions.NotFoundException", 
    "message": "Not Found", 
    "path": "/names" 
} 

我只是想我的消息從服務中傳遞並返回異常。但是這沒有發生任何人可以告訴我該怎麼做。

+0

'公共類爲myService拋出NotFoundException'您能夠編譯呢?你甚至如何得到迴應? – anacron

+0

是的。我沒有放置控制器代碼。我的控制器這項服務 – user2904696

+0

感謝您糾正這個問題。而且,僅供參考:我沒有投下你的問題。 – anacron

回答

0

使用@ControllerAdvice和@ExceptionHandler的組合,可能這會幫助你。

@ControllerAdvice 
public class GlobalValidationResponse extends ResponseEntityExceptionHandler { 

    @ExceptionHandler(NotFoundException.class) 
     public ResponseEntity<?> handleEntityNotFoundException(NotFoundException ex, HttpServletRequest request, HttpServletResponse response) { 

      return ResponseEntity.status(HttpStatus.NOT_FOUND).body(new ValidationError(ex.getMessage())); 

     } 
} 

的ValidationError實體

public class ValidationError { 

    //@JsonInclude(JsonInclude.Include.NON_EMPTY) 
    private Map<String, String> errors = new HashMap<>(); 

    private String errorMessage; 

    public ValidationError() { 
     super(); 
    } 

    public ValidationError(String errorMessage) { 
     this.errorMessage = errorMessage; 
    } 

    public ValidationError(Map<String, String> errors) { 
     this.errors = errors; 
    } 

    public Map<String, String> getErrors() { 
     return errors; 
    } 

    public void setErrors(Map<String, String> errors) { 
     this.errors = errors; 
    } 

    public String getErrorMessage() { 
     return errorMessage; 
    } 
} 
+0

但是,如果您已經投入服務,我如何明確地從我的服務 – user2904696

+0

中拋出此異常 - 拋出new NotFoundException(「Name not found」); –

+0

{ 「時間戳」:1486971408978, 「狀態」:500, 「錯誤」: 「內部服務器錯誤」, 「異常」: 「javassist.NotFoundException」, 「消息」:「org.springframework.web。 util.NestedServletException:請求處理失敗;嵌套異常是javassist.NotFoundException:vfcd「, 」path「:」/ names「 } – user2904696