@ResponseStatus 用於修飾一個類或者一個方法,修飾一個類的時候,一般修飾的是一個異常類,如下,
- 聲明一個異常類在類上面加上ResponseStatus注解,就表明,在系統運行期間,拋出AuthException的時候,就會使用這里生命的 error code 和 error reasoon 返回給客戶端,提高可讀性。
package com.kolin.sample;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
/**
* 自定義異常類
*
* @author Administrator
*
*/
@ResponseStatus(value = HttpStatus.FORBIDDEN, reason = "Are you okay?")
public class AuthException extends RuntimeException {
private static final long serialVersionUID = 5759027883028274330L;
}
- 在 控制器方法中,拋出一個 AuthException異常。
package com.kolin.sample;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller("/")
public class SampleControoler {
@RequestMapping("/")
@ResponseBody
String home() {
return "Hello World!";
}
/**
* 測試拋出異常
*
* @return
*/
@RequestMapping("/say")
@ResponseBody
String say() {
throw new AuthException();
}
}
- 運行系統,查看結果