Spring MVC 處理異常

Spring MVC 處理異常

將異常映射爲HTTP狀態碼

映射前

public class MyException extends RuntimeException {
	private static final long serialVersionUID = 1L;
}

@Component
@RequestMapping
public class Controller {
	@RequestMapping(value = "/exception", method = RequestMethod.GET)
	public void exception() {
		throw new MyException();
	}
}

映射後

import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;

@ResponseStatus(value = HttpStatus.NOT_FOUND, reason = "404")
public class MyException extends RuntimeException {
	private static final long serialVersionUID = 1L;
}

Controller 類不變


編寫異常處理的方法

import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Component
@RequestMapping
public class Controller {
	@RequestMapping(value = "/exception", method = RequestMethod.GET)
	public void exception() {
		throw new RuntimeException();
	}

	@ExceptionHandler(RuntimeException.class)
	public String handleException() {
		return "error.jsp";
	}
}

爲控制器添加通知

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

@ControllerAdvice
public class Advice {
	@ExceptionHandler(RuntimeException.class)
	public String handleException() {
		return "error.jsp";
	}
}

import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Component
@RequestMapping
public class Controller {
	@RequestMapping(value = "/exception", method = RequestMethod.GET)
	public void exception() {
		throw new RuntimeException();
	}
}

與添加映射方法同樣的效果

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章