2017-07-27 133 views
0

我想在基於spring啓動的web服務中記錄異常。彈簧啓動異常詳細信息

所以我用GlobalExceptionHandler 我的代碼:

@ControllerAdvice 
@RestController 
public class GlobalExceptionHandler { 

    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) 
    @ExceptionHandler(value = Exception.class) 
    public String handleException(Exception e){ 

     System.out.println("Ankit == "+e.getMessage()); 
     StringWriter errors = new StringWriter(); 
     e.printStackTrace(new PrintWriter(errors)); 
     System.out.println(errors.toString()); 
     return e.getMessage(); 
    } 
} 

代碼工作正常。我想要的是異常細節。我的意思是發生異常的代碼?文件名/行?或者我必須解析堆棧跟蹤?我的意思是春季開機必須爲此考慮一些事情?

+1

Afaik spring沒有任何東西來解析異常,以便找到發生異常的行。最好的辦法是迭代堆棧跟蹤,檢查包名,並選擇你感興趣的內容(行信息也將包含在那裏,以便你可以根據需要形成消息)。 – Edd

回答

-1

使用IDE

如果使用那麼任何IDE去Console Window

  1. 清除控制檯
  2. 導致異常
  3. 重複動作
  4. Console(CTRL + F)搜索ERROR
  5. 查找上述(查找2-3行,如果你沒有找到直接的線以上)包含ERROR的行。該行具有類的詳細信息,方法發生了異常。

不看控制檯或日誌

如果你想在生產中使用它,然後,處理ATLEAST已知的例外(如BAD_REQUEST,NOT_FOUND等),它在後面做可能會有所幫助的方式(添加一個額外的參數異常類)

Employee employee = employeeService.getEmployeeById(employeeId); 
if (null == employee) { 
logger.error("No tenant exists for employeeId:"+employeeId); 
throw new ObjectNotFoundException("Emplyee Not Found", this.getClass().getSimpleName();)); 
} 

這裏this.getClass().getSimpleName();將作爲參數從EmployeeController類進行傳遞。因此,在ObjectNotFoundException我們可以添加一個參數ClassName和當您在GlobalExceptionHandler處理它,你可以做到這一點,因爲它在後面做,

@ControllerAdvice 
@RestController 
public class GlobalExceptionHandler { 
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) 
    @ExceptionHandler(value = Exception.class) 
    public String handleException(Exception e){ 

     System.out.println("Ankit == "+e.getMessage()); 
     StringWriter errors = new StringWriter(); 
     e.printStackTrace(new PrintWriter(errors)); 
     String classWithExceptionName = e.getClassName(); 
     // you need to add this above getter method to your Exception Class 
     System.out.println(errors.toString()); 
     return e.getMessage(); 
    } 
} 

這是已知的常見異常。我們需要將extra parameter(ClassName)添加到您正在拋出的所有自定義異常中,這可能只是一些額外的代碼,但我認爲這是一種方式。希望現在有幫助。

+0

我需要在生產中使用這個, –

+0

哦..你沒有提到那..然後你將不得不在控制器端檢查任何異常..至少已知的異常..否則,解析堆棧跟蹤將是選項.. @ Ankit我的錯誤答案 – rdj7

+0

@AnkitBansal編輯似乎有幫助嗎? – rdj7